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