]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
rename InsetBase to Inset
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
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 "bufferview_funcs.h"
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "gettext.h"
34 #include "Intl.h"
35 #include "InsetIterator.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "LyXLayout.h"
43 #include "LyXText.h"
44 #include "LyXTextClass.h"
45 #include "LyXRC.h"
46 #include "Session.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
51 #include "TexRow.h"
52 #include "toc.h"
53 #include "Undo.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
74
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
77
78 #include <functional>
79 #include <vector>
80
81
82 namespace lyx {
83
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
93
94 using std::distance;
95 using std::endl;
96 using std::istringstream;
97 using std::make_pair;
98 using std::min;
99 using std::max;
100 using std::mem_fun_ref;
101 using std::string;
102 using std::vector;
103
104 namespace Alert = frontend::Alert;
105
106 namespace {
107
108 /// Return an inset of this class if it exists at the current cursor position
109 template <class T>
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
111 {
112         T * inset = 0;
113         DocIterator it = cur;
114         if (it.nextInset() &&
115             it.nextInset()->lyxCode() == code) {
116                 inset = static_cast<T*>(it.nextInset());
117         }
118         return inset;
119 }
120
121 } // anon namespace
122
123
124 BufferView::BufferView()
125         : width_(0), height_(0), buffer_(0), wh_(0),
126           cursor_(*this),
127           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128           intl_(new Intl), last_inset_(0)
129 {
130         xsel_cache_.set = false;
131         intl_->initKeyMapper(lyxrc.use_kbmap);
132 }
133
134
135 BufferView::~BufferView()
136 {
137 }
138
139
140 Buffer * BufferView::buffer() const
141 {
142         return buffer_;
143 }
144
145
146 void BufferView::setBuffer(Buffer * b)
147 {
148         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149                             << "[ b = " << b << "]" << endl;
150
151         if (buffer_) {
152                 // Save the actual cursor position and anchor inside the
153                 // buffer so that it can be restored in case we rechange
154                 // to this buffer later on.
155                 buffer_->saveCursor(cursor_.selectionBegin(),
156                                     cursor_.selectionEnd());
157                 // update bookmark pit of the current buffer before switch
158                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159                         BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160                         if (buffer()->fileName() != bm.filename.absFilename())
161                                 continue;
162                         // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163                         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
164                         pit_type new_pit;
165                         pos_type new_pos;
166                         int new_id;
167                         boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168                         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169                                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
170                 }
171                 // current buffer is going to be switched-off, save cursor pos
172                 // Ideally, the whole cursor stack should be saved, but session
173                 // currently can only handle bottom (whole document) level pit and pos.
174                 // That is to say, if a cursor is in a nested inset, it will be
175                 // restore to the left of the top level inset.
176                 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177                         boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
178         }
179
180         // If we're quitting lyx, don't bother updating stuff
181         if (quitting) {
182                 buffer_ = 0;
183                 return;
184         }
185
186         // If we are closing current buffer, switch to the first in
187         // buffer list.
188         if (!b) {
189                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
190                                     << " No Buffer!" << endl;
191                 // We are closing the buffer, use the first buffer as current
192                 buffer_ = theBufferList().first();
193         } else {
194                 // Set current buffer
195                 buffer_ = b;
196         }
197
198         // Reset old cursor
199         cursor_ = Cursor(*this);
200         anchor_ref_ = 0;
201         offset_ref_ = 0;
202
203         if (buffer_) {
204                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
205                                     << "Buffer addr: " << buffer_ << endl;
206                 cursor_.push(buffer_->inset());
207                 cursor_.resetAnchor();
208                 buffer_->text().setCurrentFont(cursor_);
209                 if (buffer_->getCursor().size() > 0 &&
210                     buffer_->getAnchor().size() > 0)
211                 {
212                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
213                         cursor_.resetAnchor();
214                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
215                         cursor_.setSelection();
216                         // do not set selection to the new buffer because we
217                         // only paste recent selection.
218                 }
219         }
220
221         if (buffer_)
222                 updateMetrics(false);    
223
224         if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
225                 graphics::Previews::get().generateBufferPreviews(*buffer_);
226 }
227
228
229 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
230 {
231         // File already open?
232         if (theBufferList().exists(filename.absFilename())) {
233                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
234                 docstring text = bformat(_("The document %1$s is already "
235                                                      "loaded.\n\nDo you want to revert "
236                                                      "to the saved version?"), file);
237                 int const ret = Alert::prompt(_("Revert to saved document?"),
238                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
239
240                 if (ret != 0) {
241                         setBuffer(theBufferList().getBuffer(filename.absFilename()));
242                         return true;
243                 }
244                 // FIXME: should be LFUN_REVERT
245                 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
246                         return false;
247                 // Fall through to new load. (Asger)
248                 buffer_ = 0;
249         }
250
251         Buffer * b = 0;
252
253         if (isFileReadable(filename)) {
254                 b = theBufferList().newBuffer(filename.absFilename());
255                 if (!lyx::loadLyXFile(b, filename)) {
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(filename.absFilename()));
263                 int const ret = Alert::prompt(_("Create new document?"),
264                          text, 0, 1, _("&Create"), _("Cancel"));
265
266                 if (ret == 0) {
267                         b = newFile(filename.absFilename(), 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         // Update the labels and section numbering.
279         updateLabels(*buffer_);
280         // scroll to the position when the file was last closed
281         if (lyxrc.use_lastfilepos) {
282                 pit_type pit;
283                 pos_type pos;
284                 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
285                 // if successfully move to pit (returned par_id is not zero), update metrics and reset font
286                 if (moveToPosition(pit, pos, 0, 0).get<1>()) {
287                         if (fitCursor())
288                                 updateMetrics(false);
289                         buffer_->text().setCurrentFont(cursor_);
290                 }
291         }
292
293         if (tolastfiles)
294                 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
295
296         return true;
297 }
298
299
300 void BufferView::resize()
301 {
302         if (!buffer_)
303                 return;
304
305         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
306
307         updateMetrics(false);
308         switchKeyMap();
309 }
310
311
312 bool BufferView::fitCursor()
313 {
314         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
315                 frontend::FontMetrics const & fm =
316                         theFontMetrics(cursor_.getFont());
317                 int const asc = fm.maxAscent();
318                 int const des = fm.maxDescent();
319                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
320                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
321                         return false;
322         }
323         center();
324         return true;
325 }
326
327
328 bool BufferView::multiParSel()
329 {
330         if (!cursor_.selection())
331                 return false;
332         bool ret = multiparsel_cache_;
333         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
334         // Either this, or previous selection spans paragraphs
335         return ret || multiparsel_cache_;
336 }
337
338
339 bool BufferView::update(Update::flags flags)
340 {
341         // last_inset_ points to the last visited inset. This pointer may become
342         // invalid because of keyboard editing. Since all such operations
343         // causes screen update(), I reset last_inset_ to avoid such a problem.
344         last_inset_ = 0;
345         // This is close to a hot-path.
346         LYXERR(Debug::DEBUG)
347                 << BOOST_CURRENT_FUNCTION
348                 << "[fitcursor = " << (flags & Update::FitCursor)
349                 << ", forceupdate = " << (flags & Update::Force)
350                 << ", singlepar = " << (flags & Update::SinglePar)
351                 << "]  buffer: " << buffer_ << endl;
352
353         // Check needed to survive LyX startup
354         if (!buffer_)
355                 return false;
356
357         LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
358
359         // Update macro store
360         if (!(cursor().inMathed() && cursor().inMacroMode()))
361                 buffer_->buildMacros();
362
363         // Now do the first drawing step if needed. This consists on updating
364         // the CoordCache in updateMetrics().
365         // The second drawing step is done in WorkArea::redraw() if needed.
366
367         // Case when no explicit update is requested.
368         if (!flags) {
369                 // no need to redraw anything.
370                 metrics_info_.update_strategy = NoScreenUpdate;
371                 return false;
372         }
373
374         if (flags == Update::Decoration) {
375                 metrics_info_.update_strategy = DecorationUpdate;
376                 return true;
377         }
378
379         if (flags == Update::FitCursor 
380                 || flags == (Update::Decoration | Update::FitCursor)) {
381                 bool const fit_cursor = fitCursor();
382                 // tell the frontend to update the screen if needed.
383                 if (fit_cursor) {
384                         updateMetrics(false);
385                         return true;
386                 }
387                 if (flags & Update::Decoration) {
388                         metrics_info_.update_strategy = DecorationUpdate;
389                         return true;
390                 }
391                 // no screen update is needed.
392                 metrics_info_.update_strategy = NoScreenUpdate;
393                 return false;
394         }
395
396         bool full_metrics = flags & Update::Force;
397         if (flags & Update::MultiParSel)
398                 full_metrics |= multiParSel();
399
400         bool const single_par = !full_metrics;
401         updateMetrics(single_par);
402
403         if (flags & Update::FitCursor && fitCursor())
404                 updateMetrics(false);
405
406         // tell the frontend to update the screen.
407         return true;
408 }
409
410
411 void BufferView::updateScrollbar()
412 {
413         if (!buffer_) {
414                 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
415                                      << " no text in updateScrollbar" << endl;
416                 scrollbarParameters_.reset();
417                 return;
418         }
419
420         LyXText & t = buffer_->text();
421         TextMetrics & tm = text_metrics_[&t];
422
423         int const parsize = int(t.paragraphs().size() - 1);
424         if (anchor_ref_ >  parsize)  {
425                 anchor_ref_ = parsize;
426                 offset_ref_ = 0;
427         }
428
429         LYXERR(Debug::GUI)
430                 << BOOST_CURRENT_FUNCTION
431                 << " Updating scrollbar: height: " << t.paragraphs().size()
432                 << " curr par: " << cursor_.bottom().pit()
433                 << " default height " << defaultRowHeight() << endl;
434
435         // It would be better to fix the scrollbar to understand
436         // values in [0..1] and divide everything by wh
437
438         // estimated average paragraph height:
439         if (wh_ == 0)
440                 wh_ = height_ / 4;
441
442         int h = tm.parMetrics(anchor_ref_).height();
443
444         // Normalize anchor/offset (MV):
445         while (offset_ref_ > h && anchor_ref_ < parsize) {
446                 anchor_ref_++;
447                 offset_ref_ -= h;
448                 h = tm.parMetrics(anchor_ref_).height();
449         }
450         // Look at paragraph heights on-screen
451         int sumh = 0;
452         int nh = 0;
453         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
454                 if (sumh > height_)
455                         break;
456                 int const h2 = tm.parMetrics(pit).height();
457                 sumh += h2;
458                 nh++;
459         }
460
461         BOOST_ASSERT(nh);
462         int const hav = sumh / nh;
463         // More realistic average paragraph height
464         if (hav > wh_)
465                 wh_ = hav;
466
467         BOOST_ASSERT(h);
468         scrollbarParameters_.height = (parsize + 1) * wh_;
469         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
470         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
471 }
472
473
474 ScrollbarParameters const & BufferView::scrollbarParameters() const
475 {
476         return scrollbarParameters_;
477 }
478
479
480 void BufferView::scrollDocView(int value)
481 {
482         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
483                            << "[ value = " << value << "]" << endl;
484
485         if (!buffer_)
486                 return;
487
488         LyXText & t = buffer_->text();
489         TextMetrics & tm = text_metrics_[&t];
490
491         float const bar = value / float(wh_ * t.paragraphs().size());
492
493         anchor_ref_ = int(bar * t.paragraphs().size());
494         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
495                 anchor_ref_ = int(t.paragraphs().size()) - 1;
496
497         tm.redoParagraph(anchor_ref_);
498         int const h = tm.parMetrics(anchor_ref_).height();
499         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
500         updateMetrics(false);
501 }
502
503
504 void BufferView::setCursorFromScrollbar()
505 {
506         if (!buffer_)
507                 return;
508
509         LyXText & t = buffer_->text();
510
511         int const height = 2 * defaultRowHeight();
512         int const first = height;
513         int const last = height_ - height;
514         Cursor & cur = cursor_;
515
516         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
517
518         switch (st) {
519         case bv_funcs::CUR_ABOVE:
520                 // We reset the cursor because bv_funcs::status() does not
521                 // work when the cursor is within mathed.
522                 cur.reset(buffer_->inset());
523                 t.setCursorFromCoordinates(cur, 0, first);
524                 cur.clearSelection();
525                 break;
526         case bv_funcs::CUR_BELOW:
527                 // We reset the cursor because bv_funcs::status() does not
528                 // work when the cursor is within mathed.
529                 cur.reset(buffer_->inset());
530                 t.setCursorFromCoordinates(cur, 0, last);
531                 cur.clearSelection();
532                 break;
533         case bv_funcs::CUR_INSIDE:
534                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
535                 int const newy = min(last, max(y, first));
536                 if (y != newy) {
537                         cur.reset(buffer_->inset());
538                         t.setCursorFromCoordinates(cur, 0, newy);
539                 }
540         }
541 }
542
543
544 Change const BufferView::getCurrentChange() const
545 {
546         if (!cursor_.selection())
547                 return Change(Change::UNCHANGED);
548
549         DocIterator dit = cursor_.selectionBegin();
550         return dit.paragraph().lookupChange(dit.pos());
551 }
552
553
554 void BufferView::saveBookmark(unsigned int idx)
555 {
556         // tenatively save bookmark, id and pos will be used to
557         // acturately locate a bookmark in a 'live' lyx session.
558         // pit and pos will be updated with bottom level pit/pos 
559         // when lyx exits.
560         LyX::ref().session().bookmarks().save(
561                 FileName(buffer_->fileName()),
562                 cursor_.bottom().pit(),
563                 cursor_.bottom().pos(),
564                 cursor_.paragraph().id(),
565                 cursor_.pos(),
566                 idx
567         );
568         if (idx)
569                 // emit message signal.
570                 message(_("Save bookmark"));
571 }
572
573
574 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
575         int top_id, pos_type top_pos)
576 {
577         cursor_.clearSelection();
578
579         // if a valid par_id is given, try it first
580         // This is the case for a 'live' bookmark when unique paragraph ID
581         // is used to track bookmarks.
582         if (top_id > 0) {
583                 ParIterator par = buffer_->getParFromID(top_id);
584                 if (par != buffer_->par_iterator_end()) {
585                         DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
586                         // Some slices of the iterator may not be reachable (e.g. closed collapsable inset)
587                         // so the dociterator may need to be shortened. Otherwise, setCursor may
588                         // crash lyx when the cursor can not be set to these insets.
589                         size_t const n = dit.depth();
590                         for (size_t i = 0; i < n; ++i)
591                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
592                                         dit.resize(i);
593                                         break;
594                                 }
595                         setCursor(dit);
596                         // Note: return bottom (document) level pit.
597                         return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
598                 }
599         }
600         // if top_id == 0, or searching through top_id failed
601         // This is the case for a 'restored' bookmark when only bottom 
602         // (document level) pit was saved. Because of this, bookmark
603         // restoration is inaccurate. If a bookmark was within an inset,
604         // it will be restored to the left of the outmost inset that contains
605         // the bookmark.
606         if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
607                 ParIterator it = buffer_->par_iterator_begin();
608                 ParIterator const end = buffer_->par_iterator_end();
609                 for (; it != end; ++it)
610                         if (it.pit() == bottom_pit) {
611                                 // restored pos may be bigger than it->size
612                                 setCursor(makeDocIterator(it, min(bottom_pos, it->size())));
613                                 return boost::make_tuple(bottom_pit, bottom_pos, it->id());
614                         }
615         }
616         // both methods fail
617         return boost::make_tuple(pit_type(0), pos_type(0), 0);
618 }
619
620
621 void BufferView::switchKeyMap()
622 {
623         if (!lyxrc.rtl_support)
624                 return;
625
626         if (cursor_.innerText()->real_current_font.isRightToLeft()) {
627                 if (intl_->keymap == Intl::PRIMARY)
628                         intl_->keyMapSec();
629         } else {
630                 if (intl_->keymap == Intl::SECONDARY)
631                         intl_->keyMapPrim();
632         }
633 }
634
635
636 int BufferView::workWidth() const
637 {
638         return width_;
639 }
640
641
642 void BufferView::center()
643 {
644         CursorSlice & bot = cursor_.bottom();
645         TextMetrics & tm = text_metrics_[bot.text()];
646         pit_type const pit = bot.pit();
647         tm.redoParagraph(pit);
648         ParagraphMetrics const & pm = tm.parMetrics(pit);
649         anchor_ref_ = pit;
650         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
651                 + pm.ascent() - height_ / 2;
652 }
653
654
655 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
656 {
657         FuncStatus flag;
658
659         switch (cmd.action) {
660
661         case LFUN_UNDO:
662                 flag.enabled(!buffer_->undostack().empty());
663                 break;
664         case LFUN_REDO:
665                 flag.enabled(!buffer_->redostack().empty());
666                 break;
667         case LFUN_FILE_INSERT:
668         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
669         case LFUN_FILE_INSERT_PLAINTEXT:
670         case LFUN_BOOKMARK_SAVE:
671                 // FIXME: Actually, these LFUNS should be moved to LyXText
672                 flag.enabled(cursor_.inTexted());
673                 break;
674         case LFUN_FONT_STATE:
675         case LFUN_LABEL_INSERT:
676         case LFUN_PARAGRAPH_GOTO:
677         // FIXME handle non-trivially
678         case LFUN_OUTLINE_UP:
679         case LFUN_OUTLINE_DOWN:
680         case LFUN_OUTLINE_IN:
681         case LFUN_OUTLINE_OUT:
682         case LFUN_NOTE_NEXT:
683         case LFUN_REFERENCE_NEXT:
684         case LFUN_WORD_FIND:
685         case LFUN_WORD_REPLACE:
686         case LFUN_MARK_OFF:
687         case LFUN_MARK_ON:
688         case LFUN_MARK_TOGGLE:
689         case LFUN_SCREEN_RECENTER:
690         case LFUN_BIBTEX_DATABASE_ADD:
691         case LFUN_BIBTEX_DATABASE_DEL:
692         case LFUN_WORDS_COUNT:
693         case LFUN_NEXT_INSET_TOGGLE:
694                 flag.enabled(true);
695                 break;
696
697         case LFUN_LABEL_GOTO: {
698                 flag.enabled(!cmd.argument().empty()
699                     || getInsetByCode<InsetRef>(cursor_, Inset::REF_CODE));
700                 break;
701         }
702
703         case LFUN_CHANGES_TRACK:
704                 flag.enabled(true);
705                 flag.setOnOff(buffer_->params().trackChanges);
706                 break;
707
708         case LFUN_CHANGES_OUTPUT:
709                 flag.enabled(buffer_ && LaTeXFeatures::isAvailable("dvipost"));
710                 flag.setOnOff(buffer_->params().outputChanges);
711                 break;
712
713         case LFUN_CHANGES_MERGE:
714         case LFUN_CHANGE_NEXT:
715         case LFUN_ALL_CHANGES_ACCEPT:
716         case LFUN_ALL_CHANGES_REJECT:
717                 // TODO: context-sensitive enabling of LFUNs
718                 // In principle, these command should only be enabled if there
719                 // is a change in the document. However, without proper
720                 // optimizations, this will inevitably result in poor performance.
721                 flag.enabled(buffer_);
722                 break;
723
724         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
725                 flag.setOnOff(buffer_->params().compressed);
726                 break;
727         }
728
729         default:
730                 flag.enabled(false);
731         }
732
733         return flag;
734 }
735
736
737 Update::flags BufferView::dispatch(FuncRequest const & cmd)
738 {
739         //lyxerr << BOOST_CURRENT_FUNCTION
740         //       << [ cmd = " << cmd << "]" << endl;
741
742         // Make sure that the cached BufferView is correct.
743         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
744                 << " action[" << cmd.action << ']'
745                 << " arg[" << to_utf8(cmd.argument()) << ']'
746                 << " x[" << cmd.x << ']'
747                 << " y[" << cmd.y << ']'
748                 << " button[" << cmd.button() << ']'
749                 << endl;
750
751         // FIXME: this should not be possible.
752         if (!buffer_)
753                 return Update::None;
754
755         Cursor & cur = cursor_;
756         // Default Update flags.
757         Update::flags updateFlags = Update::Force | Update::FitCursor;
758
759         switch (cmd.action) {
760
761         case LFUN_UNDO:
762                 cur.message(_("Undo"));
763                 cur.clearSelection();
764                 if (!textUndo(*this)) {
765                         cur.message(_("No further undo information"));
766                         updateFlags = Update::None;
767                 }
768                 switchKeyMap();
769                 break;
770
771         case LFUN_REDO:
772                 cur.message(_("Redo"));
773                 cur.clearSelection();
774                 if (!textRedo(*this)) {
775                         cur.message(_("No further redo information"));
776                         updateFlags = Update::None;
777                 }
778                 switchKeyMap();
779                 break;
780
781         case LFUN_FILE_INSERT:
782                 // FIXME UNICODE
783                 menuInsertLyXFile(to_utf8(cmd.argument()));
784                 break;
785
786         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
787                 // FIXME UNICODE
788                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
789                 break;
790
791         case LFUN_FILE_INSERT_PLAINTEXT:
792                 // FIXME UNICODE
793                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
794                 break;
795
796         case LFUN_FONT_STATE:
797                 cur.message(cur.currentState());
798                 break;
799
800         case LFUN_BOOKMARK_SAVE:
801                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
802                 break;
803
804         case LFUN_LABEL_GOTO: {
805                 docstring label = cmd.argument();
806                 if (label.empty()) {
807                         InsetRef * inset =
808                                 getInsetByCode<InsetRef>(cursor_,
809                                                          Inset::REF_CODE);
810                         if (inset) {
811                                 label = inset->getParam("reference");
812                                 // persistent=false: use temp_bookmark
813                                 saveBookmark(0);
814                         }
815                 }
816
817                 if (!label.empty())
818                         gotoLabel(label);
819                 break;
820         }
821
822         case LFUN_PARAGRAPH_GOTO: {
823                 int const id = convert<int>(to_utf8(cmd.argument()));
824                 int i = 0;
825                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
826                         ParIterator par = b->getParFromID(id);
827                         if (par == b->par_iterator_end()) {
828                                 LYXERR(Debug::INFO)
829                                         << "No matching paragraph found! ["
830                                         << id << "]." << endl;
831                         } else {
832                                 LYXERR(Debug::INFO)
833                                         << "Paragraph " << par->id()
834                                         << " found in buffer `"
835                                         << b->fileName() << "'." << endl;
836
837                                 if (b == buffer_) {
838                                         // Set the cursor
839                                         setCursor(makeDocIterator(par, 0));
840                                         switchKeyMap();
841                                 } else {
842                                         // Switch to other buffer view and resend cmd
843                                         theLyXFunc().dispatch(FuncRequest(
844                                                 LFUN_BUFFER_SWITCH, b->fileName()));
845                                         theLyXFunc().dispatch(cmd);
846                                         updateFlags = Update::None;
847                                 }
848                                 break;
849                         }
850                         ++i;
851                 }
852                 break;
853         }
854
855         case LFUN_OUTLINE_UP:
856                 toc::outline(toc::Up, cursor_);
857                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
858                 updateLabels(*buffer_);
859                 break;
860         case LFUN_OUTLINE_DOWN:
861                 toc::outline(toc::Down, cursor_);
862                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
863                 updateLabels(*buffer_);
864                 break;
865         case LFUN_OUTLINE_IN:
866                 toc::outline(toc::In, cursor_);
867                 updateLabels(*buffer_);
868                 break;
869         case LFUN_OUTLINE_OUT:
870                 toc::outline(toc::Out, cursor_);
871                 updateLabels(*buffer_);
872                 break;
873
874         case LFUN_NOTE_NEXT:
875                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
876                 break;
877
878         case LFUN_REFERENCE_NEXT: {
879                 vector<Inset_code> tmp;
880                 tmp.push_back(Inset::LABEL_CODE);
881                 tmp.push_back(Inset::REF_CODE);
882                 bv_funcs::gotoInset(this, tmp, true);
883                 break;
884         }
885
886         case LFUN_CHANGES_TRACK:
887                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
888                 break;
889
890         case LFUN_CHANGES_OUTPUT:
891                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
892                 break;
893
894         case LFUN_CHANGE_NEXT:
895                 findNextChange(this);
896                 break;
897
898         case LFUN_CHANGES_MERGE:
899                 if (findNextChange(this))
900                         showDialog("changes");
901                 break;
902
903         case LFUN_ALL_CHANGES_ACCEPT:
904                 // select complete document
905                 cursor_.reset(buffer_->inset());
906                 cursor_.selHandle(true);
907                 buffer_->text().cursorBottom(cursor_);
908                 // accept everything in a single step to support atomic undo
909                 buffer_->text().acceptOrRejectChanges(cursor_, LyXText::ACCEPT);
910                 break;
911
912         case LFUN_ALL_CHANGES_REJECT:
913                 // select complete document
914                 cursor_.reset(buffer_->inset());
915                 cursor_.selHandle(true);
916                 buffer_->text().cursorBottom(cursor_);
917                 // reject everything in a single step to support atomic undo
918                 // Note: reject does not work recursively; the user may have to repeat the operation
919                 buffer_->text().acceptOrRejectChanges(cursor_, LyXText::REJECT);
920                 break;
921
922         case LFUN_WORD_FIND:
923                 find(this, cmd);
924                 break;
925
926         case LFUN_WORD_REPLACE:
927                 replace(this, cmd);
928                 break;
929
930         case LFUN_MARK_OFF:
931                 cur.clearSelection();
932                 cur.resetAnchor();
933                 cur.message(from_utf8(N_("Mark off")));
934                 break;
935
936         case LFUN_MARK_ON:
937                 cur.clearSelection();
938                 cur.mark() = true;
939                 cur.resetAnchor();
940                 cur.message(from_utf8(N_("Mark on")));
941                 break;
942
943         case LFUN_MARK_TOGGLE:
944                 cur.clearSelection();
945                 if (cur.mark()) {
946                         cur.mark() = false;
947                         cur.message(from_utf8(N_("Mark removed")));
948                 } else {
949                         cur.mark() = true;
950                         cur.message(from_utf8(N_("Mark set")));
951                 }
952                 cur.resetAnchor();
953                 break;
954
955         case LFUN_SCREEN_RECENTER:
956                 center();
957                 break;
958
959         case LFUN_BIBTEX_DATABASE_ADD: {
960                 Cursor tmpcur = cursor_;
961                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
962                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
963                                                 Inset::BIBTEX_CODE);
964                 if (inset) {
965                         if (inset->addDatabase(to_utf8(cmd.argument())))
966                                 buffer_->updateBibfilesCache();
967                 }
968                 break;
969         }
970
971         case LFUN_BIBTEX_DATABASE_DEL: {
972                 Cursor tmpcur = cursor_;
973                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
974                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
975                                                 Inset::BIBTEX_CODE);
976                 if (inset) {
977                         if (inset->delDatabase(to_utf8(cmd.argument())))
978                                 buffer_->updateBibfilesCache();
979                 }
980                 break;
981         }
982
983         case LFUN_WORDS_COUNT: {
984                 DocIterator from, to;
985                 if (cur.selection()) {
986                         from = cur.selectionBegin();
987                         to = cur.selectionEnd();
988                 } else {
989                         from = doc_iterator_begin(buffer_->inset());
990                         to = doc_iterator_end(buffer_->inset());
991                 }
992                 int const count = countWords(from, to);
993                 docstring message;
994                 if (count != 1) {
995                         if (cur.selection())
996                                 message = bformat(_("%1$d words in selection."),
997                                           count);
998                                 else
999                                         message = bformat(_("%1$d words in document."),
1000                                                           count);
1001                 }
1002                 else {
1003                         if (cur.selection())
1004                                 message = _("One word in selection.");
1005                         else
1006                                 message = _("One word in document.");
1007                 }
1008
1009                 Alert::information(_("Count words"), message);
1010         }
1011                 break;
1012
1013         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1014                 // turn compression on/off
1015                 buffer_->params().compressed = !buffer_->params().compressed;
1016                 break;
1017
1018         case LFUN_NEXT_INSET_TOGGLE: {
1019                 // this is the real function we want to invoke
1020                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1021                 // if there is an inset at cursor, see whether it
1022                 // wants to toggle.
1023                 Inset * inset = cur.nextInset();
1024                 if (inset && inset->isActive()) {
1025                         Cursor tmpcur = cur;
1026                         tmpcur.pushLeft(*inset);
1027                         inset->dispatch(tmpcur, tmpcmd);
1028                         if (tmpcur.result().dispatched()) {
1029                                 cur.dispatched();
1030                         }
1031                 }
1032                 // if it did not work, try the underlying inset.
1033                 if (!cur.result().dispatched())
1034                         cur.dispatch(tmpcmd);
1035
1036                 if (cur.result().dispatched())
1037                         cur.clearSelection();
1038
1039                 break;
1040         }
1041
1042         default:
1043                 updateFlags = Update::None;
1044         }
1045
1046         return updateFlags;
1047 }
1048
1049
1050 docstring const BufferView::requestSelection()
1051 {
1052         if (!buffer_)
1053                 return docstring();
1054
1055         Cursor & cur = cursor_;
1056
1057         if (!cur.selection()) {
1058                 xsel_cache_.set = false;
1059                 return docstring();
1060         }
1061
1062         if (!xsel_cache_.set ||
1063             cur.top() != xsel_cache_.cursor ||
1064             cur.anchor_.top() != xsel_cache_.anchor)
1065         {
1066                 xsel_cache_.cursor = cur.top();
1067                 xsel_cache_.anchor = cur.anchor_.top();
1068                 xsel_cache_.set = cur.selection();
1069                 return cur.selectionAsString(false);
1070         }
1071         return docstring();
1072 }
1073
1074
1075 void BufferView::clearSelection()
1076 {
1077         if (buffer_) {
1078                 cursor_.clearSelection();
1079                 // Clear the selection buffer. Otherwise a subsequent
1080                 // middle-mouse-button paste would use the selection buffer,
1081                 // not the more current external selection.
1082                 cap::clearSelection();
1083                 xsel_cache_.set = false;
1084                 // The buffer did not really change, but this causes the
1085                 // redraw we need because we cleared the selection above.
1086                 buffer_->changed();
1087         }
1088 }
1089
1090
1091 void BufferView::workAreaResize(int width, int height)
1092 {
1093         // Update from work area
1094         width_ = width;
1095         height_ = height;
1096
1097         // The complete text metrics will be redone.
1098         text_metrics_.clear();
1099
1100         if (buffer_)
1101                 resize();
1102 }
1103
1104
1105 Inset const * BufferView::getCoveringInset(LyXText const & text, int x, int y)
1106 {
1107         pit_type pit = text.getPitNearY(*this, y);
1108         BOOST_ASSERT(pit != -1);
1109         Paragraph const & par = text.getPar(pit);
1110
1111         LYXERR(Debug::DEBUG)
1112                 << BOOST_CURRENT_FUNCTION
1113                 << ": x: " << x
1114                 << " y: " << y
1115                 << "  pit: " << pit
1116                 << endl;
1117         InsetList::const_iterator iit = par.insetlist.begin();
1118         InsetList::const_iterator iend = par.insetlist.end();
1119         for (; iit != iend; ++iit) {
1120                 Inset * const inset = iit->inset;
1121                 if (inset->covers(*this, x, y)) {
1122                         if (!inset->descendable())
1123                                 // No need to go further down if the inset is not 
1124                                 // descendable.
1125                                 return inset;
1126
1127                         size_t cell_number = inset->nargs();
1128                         // Check all the inner cell.
1129                         for (size_t i = 0; i != cell_number; ++i) {
1130                                 LyXText const * inner_text = inset->getText(i);
1131                                 if (inner_text) {
1132                                         // Try deeper.
1133                                         Inset const * inset_deeper = 
1134                                                 getCoveringInset(*inner_text, x, y);
1135                                         if (inset_deeper)
1136                                                 return inset_deeper;
1137                                 }
1138                         }
1139
1140                         LYXERR(Debug::DEBUG)
1141                                 << BOOST_CURRENT_FUNCTION
1142                                 << ": Hit inset: " << inset << endl;
1143                         return inset;
1144                 }
1145         }
1146         LYXERR(Debug::DEBUG)
1147                 << BOOST_CURRENT_FUNCTION
1148                 << ": No inset hit. " << endl;
1149         return 0;
1150 }
1151
1152
1153 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1154 {
1155         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1156
1157         // This is only called for mouse related events including
1158         // LFUN_FILE_OPEN generated by drag-and-drop.
1159         FuncRequest cmd = cmd0;
1160
1161         // E.g. Qt mouse press when no buffer
1162         if (!buffer_)
1163                 return false;
1164
1165         Cursor cur(*this);
1166         cur.push(buffer_->inset());
1167         cur.selection() = cursor_.selection();
1168
1169         // Either the inset under the cursor or the
1170         // surrounding LyXText will handle this event.
1171
1172         // make sure we stay within the screen...
1173         cmd.y = min(max(cmd.y, -1), height_);
1174         
1175         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1176                 
1177                 // Get inset under mouse, if there is one.
1178                 Inset const * covering_inset = 
1179                         getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1180                 if (covering_inset == last_inset_)
1181                         // Same inset, no need to do anything...
1182                         return false;
1183
1184                 bool need_redraw = false;
1185                 // const_cast because of setMouseHover().
1186                 Inset * inset = const_cast<Inset *>(covering_inset);
1187                 if (last_inset_)
1188                         // Remove the hint on the last hovered inset (if any).
1189                         need_redraw |= last_inset_->setMouseHover(false);
1190                 if (inset)
1191                         // Highlighted the newly hovered inset (if any).
1192                         need_redraw |= inset->setMouseHover(true);
1193                 last_inset_ = inset;
1194
1195                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1196                 // not expose the button for redraw. We adjust here the metrics dimension
1197                 // to enable a full redraw.
1198                 // FIXME: It is possible to redraw only the area around the button!
1199                 if (need_redraw 
1200                         && metrics_info_.update_strategy == SingleParUpdate) {
1201                         // FIXME: It should be possible to redraw only the area around 
1202                         // the button by doing this:
1203                         //
1204                         //metrics_info_.singlepar = false;
1205                         //metrics_info_.y1 = ymin of button;
1206                         //metrics_info_.y2 = ymax of button;
1207                         //
1208                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1209                         // between background updates and text updates. So we use the hammer
1210                         // solution for now. We could also avoid the updateMetrics() below
1211                         // by using the first and last pit of the CoordCache. Have a look
1212                         // at LyXText::getPitNearY() to see what I mean.
1213                         //
1214                         //metrics_info_.pit1 = first pit of CoordCache;
1215                         //metrics_info_.pit2 = last pit of CoordCache;
1216                         //metrics_info_.singlepar = false;
1217                         //metrics_info_.y1 = 0;
1218                         //metrics_info_.y2 = height_;
1219                         //
1220                         updateMetrics(false);
1221                 }
1222
1223                 // This event (moving without mouse click) is not passed further.
1224                 // This should be changed if it is further utilized.
1225                 return need_redraw;
1226         }
1227         
1228         // Build temporary cursor.
1229         Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1230
1231         // Put anchor at the same position.
1232         cur.resetAnchor();
1233
1234         // Try to dispatch to an non-editable inset near this position
1235         // via the temp cursor. If the inset wishes to change the real
1236         // cursor it has to do so explicitly by using
1237         //  cur.bv().cursor() = cur;  (or similar)
1238         if (inset) {
1239                 inset->dispatch(cur, cmd);
1240         }
1241
1242         // Now dispatch to the temporary cursor. If the real cursor should
1243         // be modified, the inset's dispatch has to do so explicitly.
1244         if (!cur.result().dispatched())
1245                 cur.dispatch(cmd);
1246
1247         // Redraw if requested and necessary.
1248         if (cur.result().dispatched() && cur.result().update())
1249                 return update(cur.result().update());
1250
1251         return false;
1252 }
1253
1254
1255 void BufferView::scroll(int /*lines*/)
1256 {
1257 //      if (!buffer_)
1258 //              return;
1259 //
1260 //      LyXText const * t = &buffer_->text();
1261 //      int const line_height = defaultRowHeight();
1262 //
1263 //      // The new absolute coordinate
1264 //      int new_top_y = top_y() + lines * line_height;
1265 //
1266 //      // Restrict to a valid value
1267 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1268 //      new_top_y = std::max(0, new_top_y);
1269 //
1270 //      scrollDocView(new_top_y);
1271 //
1272 }
1273
1274
1275 void BufferView::setCursorFromRow(int row)
1276 {
1277         int tmpid = -1;
1278         int tmppos = -1;
1279
1280         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1281
1282         if (tmpid == -1)
1283                 buffer_->text().setCursor(cursor_, 0, 0);
1284         else
1285                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1286 }
1287
1288
1289 void BufferView::gotoLabel(docstring const & label)
1290 {
1291         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1292                 vector<docstring> labels;
1293                 it->getLabelList(*buffer_, labels);
1294                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1295                         setCursor(it);
1296                         update();
1297                         return;
1298                 }
1299         }
1300 }
1301
1302
1303 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1304 {
1305         return const_cast<BufferView *>(this)->textMetrics(t);
1306 }
1307
1308
1309 TextMetrics & BufferView::textMetrics(LyXText const * t)
1310 {
1311         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1312         if (tmc_it == text_metrics_.end()) {
1313                 tmc_it = text_metrics_.insert(
1314                         make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1315         }       
1316         return tmc_it->second;
1317 }
1318
1319
1320 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1321                 pit_type pit) const
1322 {
1323         return textMetrics(t).parMetrics(pit);
1324 }
1325
1326
1327 int BufferView::workHeight() const
1328 {
1329         return height_;
1330 }
1331
1332
1333 void BufferView::setCursor(DocIterator const & dit)
1334 {
1335         size_t const n = dit.depth();
1336         for (size_t i = 0; i < n; ++i)
1337                 dit[i].inset().edit(cursor_, true);
1338
1339         cursor_.setCursor(dit);
1340         cursor_.selection() = false;
1341 }
1342
1343
1344 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1345 {
1346         // Would be wrong to delete anything if we have a selection.
1347         if (cur.selection())
1348                 return false;
1349
1350         bool need_anchor_change = false;
1351         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1352                 need_anchor_change);
1353
1354         if (need_anchor_change)
1355                 cur.resetAnchor();
1356         
1357         if (!changed)
1358                 return false;
1359
1360         updateLabels(*buffer_);
1361
1362         updateMetrics(false);
1363         buffer_->changed();
1364         return true;
1365 }
1366
1367
1368 bool BufferView::mouseSetCursor(Cursor & cur)
1369 {
1370         BOOST_ASSERT(&cur.bv() == this);
1371
1372         // Has the cursor just left the inset?
1373         bool badcursor = false;
1374         bool leftinset = (&cursor_.inset() != &cur.inset());
1375         if (leftinset)
1376                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1377
1378         // do the dEPM magic if needed
1379         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1380         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1381         // the leftinset bool would not be necessary (badcursor instead).
1382         bool update = leftinset;
1383         if (!badcursor && cursor_.inTexted())
1384                 update |= checkDepm(cur, cursor_);
1385
1386         // if the cursor was in an empty script inset and the new
1387         // position is in the nucleus of the inset, notifyCursorLeaves
1388         // will kill the script inset itself. So we check all the
1389         // elements of the cursor to make sure that they are correct.
1390         // For an example, see bug 2933: 
1391         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1392         // The code below could maybe be moved to a DocIterator method.
1393         //lyxerr << "cur before " << cur <<std::endl;
1394         DocIterator dit(cur.inset());
1395         dit.push_back(cur.bottom());
1396         size_t i = 1;
1397         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1398                 dit.push_back(cur[i]);
1399                 ++i;
1400         }
1401         //lyxerr << "5 cur after" << dit <<std::endl;
1402
1403         cursor_.setCursor(dit);
1404         cursor_.clearSelection();
1405         finishUndo();
1406         return update;
1407 }
1408
1409
1410 void BufferView::putSelectionAt(DocIterator const & cur,
1411                                 int length, bool backwards)
1412 {
1413         cursor_.clearSelection();
1414
1415         setCursor(cur);
1416
1417         if (length) {
1418                 if (backwards) {
1419                         cursor_.pos() += length;
1420                         cursor_.setSelection(cursor_, -length);
1421                 } else
1422                         cursor_.setSelection(cursor_, length);
1423                 cap::saveSelection(cursor_);
1424         }
1425 }
1426
1427
1428 Cursor & BufferView::cursor()
1429 {
1430         return cursor_;
1431 }
1432
1433
1434 Cursor const & BufferView::cursor() const
1435 {
1436         return cursor_;
1437 }
1438
1439
1440 pit_type BufferView::anchor_ref() const
1441 {
1442         return anchor_ref_;
1443 }
1444
1445
1446 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1447 {
1448         return metrics_info_;
1449 }
1450
1451
1452 // FIXME: We should split-up updateMetrics() for the singlepar case.
1453 void BufferView::updateMetrics(bool singlepar)
1454 {
1455         LyXText & buftext = buffer_->text();
1456         TextMetrics & tm = textMetrics(&buftext);
1457         pit_type size = int(buftext.paragraphs().size());
1458
1459         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1460                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1461                 offset_ref_ = 0;
1462         }
1463         
1464         // If the paragraph metrics has changed, we can not
1465         // use the singlepar optimisation.
1466         if (singlepar
1467                 // In Single Paragraph mode, rebreak only
1468                 // the (main text, not inset!) paragraph containing the cursor.
1469                 // (if this paragraph contains insets etc., rebreaking will
1470                 // recursively descend)
1471                 && tm.redoParagraph(cursor_.bottom().pit()))
1472                 singlepar = false;
1473
1474         pit_type const pit = anchor_ref_;
1475         int pit1 = pit;
1476         int pit2 = pit;
1477         size_t const npit = buftext.paragraphs().size();
1478
1479         // Rebreak anchor paragraph.
1480         if (!singlepar)
1481                 tm.redoParagraph(pit);
1482         
1483         // Clear out the position cache in case of full screen redraw.
1484         if (!singlepar)
1485                 coord_cache_.clear();
1486
1487         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1488
1489         // Redo paragraphs above anchor if necessary.
1490         int y1 = y0;
1491         while (y1 > 0 && pit1 > 0) {
1492                 y1 -= tm.parMetrics(pit1).ascent();
1493                 --pit1;
1494                 if (!singlepar)
1495                         tm.redoParagraph(pit1);
1496                 y1 -= tm.parMetrics(pit1).descent();
1497         }
1498
1499
1500         // Take care of ascent of first line
1501         y1 -= tm.parMetrics(pit1).ascent();
1502
1503         // Normalize anchor for next time
1504         anchor_ref_ = pit1;
1505         offset_ref_ = -y1;
1506
1507         // Grey at the beginning is ugly
1508         if (pit1 == 0 && y1 > 0) {
1509                 y0 -= y1;
1510                 y1 = 0;
1511                 anchor_ref_ = 0;
1512         }
1513
1514         // Redo paragraphs below the anchor if necessary.
1515         int y2 = y0;
1516         while (y2 < height_ && pit2 < int(npit) - 1) {
1517                 y2 += tm.parMetrics(pit2).descent();
1518                 ++pit2;
1519                 if (!singlepar)
1520                         tm.redoParagraph(pit2);
1521                 y2 += tm.parMetrics(pit2).ascent();
1522         }
1523
1524         // Take care of descent of last line
1525         y2 += tm.parMetrics(pit2).descent();
1526
1527         // The coordinates of all these paragraphs are correct, cache them
1528         int y = y1;
1529         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1530         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1531                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1532                 y += pm.ascent();
1533                 parPos[pit] = Point(0, y);
1534                 if (singlepar && pit == cursor_.bottom().pit()) {
1535                         // In Single Paragraph mode, collect here the
1536                         // y1 and y2 of the (one) paragraph the cursor is in
1537                         y1 = y - pm.ascent();
1538                         y2 = y + pm.descent();
1539                 }
1540                 y += pm.descent();
1541         }
1542
1543         if (singlepar) {
1544                 // collect cursor paragraph iter bounds
1545                 pit1 = cursor_.bottom().pit();
1546                 pit2 = cursor_.bottom().pit();
1547         }
1548
1549         LYXERR(Debug::DEBUG)
1550                 << BOOST_CURRENT_FUNCTION
1551                 << " y1: " << y1
1552                 << " y2: " << y2
1553                 << " pit1: " << pit1
1554                 << " pit2: " << pit2
1555                 << " npit: " << npit
1556                 << " singlepar: " << singlepar
1557                 << "size: " << size
1558                 << endl;
1559
1560         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, 
1561                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1562
1563         if (lyxerr.debugging(Debug::WORKAREA)) {
1564                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1565                 coord_cache_.dump();
1566         }
1567 }
1568
1569
1570 void BufferView::menuInsertLyXFile(string const & filenm)
1571 {
1572         BOOST_ASSERT(cursor_.inTexted());
1573         string filename = filenm;
1574
1575         if (filename.empty()) {
1576                 // Launch a file browser
1577                 // FIXME UNICODE
1578                 string initpath = lyxrc.document_path;
1579
1580                 if (buffer_) {
1581                         string const trypath = buffer_->filePath();
1582                         // If directory is writeable, use this as default.
1583                         if (isDirWriteable(FileName(trypath)))
1584                                 initpath = trypath;
1585                 }
1586
1587                 // FIXME UNICODE
1588                 FileDialog fileDlg(_("Select LyX document to insert"),
1589                         LFUN_FILE_INSERT,
1590                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1591                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support().absFilename(), "examples"))));
1592
1593                 FileDialog::Result result =
1594                         fileDlg.open(from_utf8(initpath),
1595                                      FileFilterList(_("LyX Documents (*.lyx)")),
1596                                      docstring());
1597
1598                 if (result.first == FileDialog::Later)
1599                         return;
1600
1601                 // FIXME UNICODE
1602                 filename = to_utf8(result.second);
1603
1604                 // check selected filename
1605                 if (filename.empty()) {
1606                         // emit message signal.
1607                         message(_("Canceled."));
1608                         return;
1609                 }
1610         }
1611
1612         // Get absolute path of file and add ".lyx"
1613         // to the filename if necessary
1614         filename = fileSearch(string(), filename, "lyx").absFilename();
1615
1616         docstring const disp_fn = makeDisplayPath(filename);
1617         // emit message signal.
1618         message(bformat(_("Inserting document %1$s..."), disp_fn));
1619
1620         docstring res;
1621         Buffer buf("", false);
1622         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1623                 ErrorList & el = buffer_->errorList("Parse");
1624                 // Copy the inserted document error list into the current buffer one.
1625                 el = buf.errorList("Parse");
1626                 recordUndo(cursor_);
1627                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1628                                              buf.params().textclass, el);
1629                 res = _("Document %1$s inserted.");
1630         } else
1631                 res = _("Could not insert document %1$s");
1632
1633         // emit message signal.
1634         message(bformat(res, disp_fn));
1635         buffer_->errors("Parse");
1636         resize();
1637 }
1638
1639 } // namespace lyx