3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.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"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
44 #include "TextClass.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
67 #include "graphics/Previews.h"
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"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
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;
96 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
113 DocIterator it = cur;
114 if (it.nextInset() &&
115 it.nextInset()->lyxCode() == code) {
116 inset = static_cast<T*>(it.nextInset());
124 BufferView::BufferView()
125 : width_(0), height_(0), buffer_(0), wh_(0),
127 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 intl_(new Intl), last_inset_(0)
130 xsel_cache_.set = false;
131 intl_->initKeyMapper(lyxrc.use_kbmap);
135 BufferView::~BufferView()
140 Buffer * BufferView::buffer() const
146 void BufferView::setBuffer(Buffer * b)
148 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
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())
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
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);
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()) );
180 // If we're quitting lyx, don't bother updating stuff
186 //FIXME Fix for bug 3440 is here.
187 // If we are closing current buffer, switch to the first in
190 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
191 << " No Buffer!" << endl;
192 // We are closing the buffer, use the first buffer as current
194 // if (last_buffer_) buffer_ = last_buffer_;
195 // also check that this is in theBufferList()?
196 buffer_ = theBufferList().first();
199 // last_buffer = buffer_;
200 // Set current buffer
205 cursor_ = Cursor(*this);
212 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
213 << "Buffer addr: " << buffer_ << endl;
214 cursor_.push(buffer_->inset());
215 cursor_.resetAnchor();
216 buffer_->text().setCurrentFont(cursor_);
217 if (buffer_->getCursor().size() > 0 &&
218 buffer_->getAnchor().size() > 0)
220 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
221 cursor_.resetAnchor();
222 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
223 cursor_.setSelection();
224 // do not set selection to the new buffer because we
225 // only paste recent selection.
227 // Make sure that the restored cursor is not broken. This can happen for
228 // example if this Buffer has been modified by another view.
229 cursor_.fixIfBroken();
231 updateMetrics(false);
232 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
233 graphics::Previews::get().generateBufferPreviews(*buffer_);
236 // FIXME There is now no need for this to be in BufferView. It should all
237 // be moved to buffer_func.cpp. (Abdel)
238 Buffer * BufferView::loadLyXFile(FileName const & filename, bool auto_open)
240 // File already open?
241 if (theBufferList().exists(filename.absFilename())) {
242 docstring const file = makeDisplayPath(filename.absFilename(), 20);
243 docstring text = bformat(_("The document %1$s is already "
244 "loaded.\n\nDo you want to revert "
245 "to the saved version?"), file);
246 int const ret = Alert::prompt(_("Revert to saved document?"),
247 text, 0, 1, _("&Revert"), _("&Switch to document"));
250 Buffer * buf = theBufferList().getBuffer(filename.absFilename());
254 // FIXME: should be LFUN_REVERT
255 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
257 // Fall through to new load. (Asger)
263 if (isFileReadable(filename)) {
264 b = theBufferList().newBuffer(filename.absFilename());
265 if (!lyx::loadLyXFile(b, filename)) {
266 theBufferList().release(b);
270 docstring text = bformat(_("The document %1$s does not yet "
271 "exist.\n\nDo you want to create "
272 "a new document?"), from_utf8(filename.absFilename()));
273 int const ret = Alert::prompt(_("Create new document?"),
274 text, 0, 1, _("&Create"), _("Cancel"));
277 b = newFile(filename.absFilename(), string(), true);
291 void BufferView::resize()
296 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
298 updateMetrics(false);
302 bool BufferView::fitCursor()
304 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
305 frontend::FontMetrics const & fm =
306 theFontMetrics(cursor_.getFont());
307 int const asc = fm.maxAscent();
308 int const des = fm.maxDescent();
309 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
310 if (p.y_ - asc >= 0 && p.y_ + des < height_)
318 bool BufferView::multiParSel()
320 if (!cursor_.selection())
322 bool ret = multiparsel_cache_;
323 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
324 // Either this, or previous selection spans paragraphs
325 return ret || multiparsel_cache_;
329 bool BufferView::update(Update::flags flags)
331 // last_inset_ points to the last visited inset. This pointer may become
332 // invalid because of keyboard editing. Since all such operations
333 // causes screen update(), I reset last_inset_ to avoid such a problem.
335 // This is close to a hot-path.
337 << BOOST_CURRENT_FUNCTION
338 << "[fitcursor = " << (flags & Update::FitCursor)
339 << ", forceupdate = " << (flags & Update::Force)
340 << ", singlepar = " << (flags & Update::SinglePar)
341 << "] buffer: " << buffer_ << endl;
343 // Check needed to survive LyX startup
347 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
349 // Update macro store
350 if (!(cursor().inMathed() && cursor().inMacroMode()))
351 buffer_->buildMacros();
353 // Now do the first drawing step if needed. This consists on updating
354 // the CoordCache in updateMetrics().
355 // The second drawing step is done in WorkArea::redraw() if needed.
357 // Case when no explicit update is requested.
359 // no need to redraw anything.
360 metrics_info_.update_strategy = NoScreenUpdate;
364 if (flags == Update::Decoration) {
365 metrics_info_.update_strategy = DecorationUpdate;
369 if (flags == Update::FitCursor
370 || flags == (Update::Decoration | Update::FitCursor)) {
371 bool const fit_cursor = fitCursor();
372 // tell the frontend to update the screen if needed.
374 updateMetrics(false);
377 if (flags & Update::Decoration) {
378 metrics_info_.update_strategy = DecorationUpdate;
381 // no screen update is needed.
382 metrics_info_.update_strategy = NoScreenUpdate;
386 bool full_metrics = flags & Update::Force;
387 if (flags & Update::MultiParSel)
388 full_metrics |= multiParSel();
390 bool const single_par = !full_metrics;
391 updateMetrics(single_par);
393 if (flags & Update::FitCursor && fitCursor())
394 updateMetrics(false);
396 // tell the frontend to update the screen.
401 void BufferView::updateScrollbar()
404 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
405 << " no text in updateScrollbar" << endl;
406 scrollbarParameters_.reset();
410 Text & t = buffer_->text();
411 TextMetrics & tm = text_metrics_[&t];
413 int const parsize = int(t.paragraphs().size() - 1);
414 if (anchor_ref_ > parsize) {
415 anchor_ref_ = parsize;
420 << BOOST_CURRENT_FUNCTION
421 << " Updating scrollbar: height: " << t.paragraphs().size()
422 << " curr par: " << cursor_.bottom().pit()
423 << " default height " << defaultRowHeight() << endl;
425 // It would be better to fix the scrollbar to understand
426 // values in [0..1] and divide everything by wh
428 // estimated average paragraph height:
432 int h = tm.parMetrics(anchor_ref_).height();
434 // Normalize anchor/offset (MV):
435 while (offset_ref_ > h && anchor_ref_ < parsize) {
438 h = tm.parMetrics(anchor_ref_).height();
440 // Look at paragraph heights on-screen
443 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
446 int const h2 = tm.parMetrics(pit).height();
452 int const hav = sumh / nh;
453 // More realistic average paragraph height
458 scrollbarParameters_.height = (parsize + 1) * wh_;
459 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
460 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
464 ScrollbarParameters const & BufferView::scrollbarParameters() const
466 return scrollbarParameters_;
470 void BufferView::scrollDocView(int value)
472 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
473 << "[ value = " << value << "]" << endl;
478 Text & t = buffer_->text();
479 TextMetrics & tm = text_metrics_[&t];
481 float const bar = value / float(wh_ * t.paragraphs().size());
483 anchor_ref_ = int(bar * t.paragraphs().size());
484 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
485 anchor_ref_ = int(t.paragraphs().size()) - 1;
487 tm.redoParagraph(anchor_ref_);
488 int const h = tm.parMetrics(anchor_ref_).height();
489 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
490 updateMetrics(false);
494 void BufferView::setCursorFromScrollbar()
499 Text & t = buffer_->text();
501 int const height = 2 * defaultRowHeight();
502 int const first = height;
503 int const last = height_ - height;
504 Cursor & cur = cursor_;
506 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
509 case bv_funcs::CUR_ABOVE:
510 // We reset the cursor because bv_funcs::status() does not
511 // work when the cursor is within mathed.
512 cur.reset(buffer_->inset());
513 t.setCursorFromCoordinates(cur, 0, first);
514 cur.clearSelection();
516 case bv_funcs::CUR_BELOW:
517 // We reset the cursor because bv_funcs::status() does not
518 // work when the cursor is within mathed.
519 cur.reset(buffer_->inset());
520 t.setCursorFromCoordinates(cur, 0, last);
521 cur.clearSelection();
523 case bv_funcs::CUR_INSIDE:
524 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
525 int const newy = min(last, max(y, first));
527 cur.reset(buffer_->inset());
528 t.setCursorFromCoordinates(cur, 0, newy);
534 Change const BufferView::getCurrentChange() const
536 if (!cursor_.selection())
537 return Change(Change::UNCHANGED);
539 DocIterator dit = cursor_.selectionBegin();
540 return dit.paragraph().lookupChange(dit.pos());
544 void BufferView::saveBookmark(unsigned int idx)
546 // tenatively save bookmark, id and pos will be used to
547 // acturately locate a bookmark in a 'live' lyx session.
548 // pit and pos will be updated with bottom level pit/pos
550 LyX::ref().session().bookmarks().save(
551 FileName(buffer_->fileName()),
552 cursor_.bottom().pit(),
553 cursor_.bottom().pos(),
554 cursor_.paragraph().id(),
559 // emit message signal.
560 message(_("Save bookmark"));
564 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
565 int top_id, pos_type top_pos)
567 cursor_.clearSelection();
569 // if a valid par_id is given, try it first
570 // This is the case for a 'live' bookmark when unique paragraph ID
571 // is used to track bookmarks.
573 ParIterator par = buffer_->getParFromID(top_id);
574 if (par != buffer_->par_iterator_end()) {
575 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
576 // Some slices of the iterator may not be
577 // reachable (e.g. closed collapsable inset)
578 // so the dociterator may need to be
579 // shortened. Otherwise, setCursor may crash
580 // lyx when the cursor can not be set to these
582 size_t const n = dit.depth();
583 for (size_t i = 0; i < n; ++i)
584 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
589 // Note: return bottom (document) level pit.
590 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
593 // if top_id == 0, or searching through top_id failed
594 // This is the case for a 'restored' bookmark when only bottom
595 // (document level) pit was saved. Because of this, bookmark
596 // restoration is inaccurate. If a bookmark was within an inset,
597 // it will be restored to the left of the outmost inset that contains
599 if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
600 DocIterator it = doc_iterator_begin(buffer_->inset());
601 it.pit() = bottom_pit;
602 it.pos() = min(bottom_pos, it.paragraph().size());
604 return boost::make_tuple(it.pit(), it.pos(),
605 it.paragraph().id());
608 return boost::make_tuple(pit_type(0), pos_type(0), 0);
612 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
614 if (lyxrc.rtl_support) {
615 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
616 if (intl_->keymap == Intl::PRIMARY)
619 if (intl_->keymap == Intl::SECONDARY)
624 intl_->getTransManager().translateAndInsert(c, t, cur);
628 int BufferView::workWidth() const
634 void BufferView::center()
636 CursorSlice & bot = cursor_.bottom();
637 TextMetrics & tm = text_metrics_[bot.text()];
638 pit_type const pit = bot.pit();
639 tm.redoParagraph(pit);
640 ParagraphMetrics const & pm = tm.parMetrics(pit);
642 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
643 + pm.ascent() - height_ / 2;
647 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
651 Cursor & cur = cursor_;
653 switch (cmd.action) {
656 flag.enabled(!buffer_->undostack().empty());
659 flag.enabled(!buffer_->redostack().empty());
661 case LFUN_FILE_INSERT:
662 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
663 case LFUN_FILE_INSERT_PLAINTEXT:
664 case LFUN_BOOKMARK_SAVE:
665 // FIXME: Actually, these LFUNS should be moved to Text
666 flag.enabled(cur.inTexted());
668 case LFUN_FONT_STATE:
669 case LFUN_LABEL_INSERT:
670 case LFUN_PARAGRAPH_GOTO:
671 // FIXME handle non-trivially
672 case LFUN_OUTLINE_UP:
673 case LFUN_OUTLINE_DOWN:
674 case LFUN_OUTLINE_IN:
675 case LFUN_OUTLINE_OUT:
677 case LFUN_REFERENCE_NEXT:
681 case LFUN_MARK_TOGGLE:
682 case LFUN_SCREEN_RECENTER:
683 case LFUN_BIBTEX_DATABASE_ADD:
684 case LFUN_BIBTEX_DATABASE_DEL:
685 case LFUN_WORDS_COUNT:
686 case LFUN_NEXT_INSET_TOGGLE:
690 case LFUN_WORD_REPLACE:
691 flag.enabled(!cur.paragraph().isDeleted(cur.pos()));
694 case LFUN_LABEL_GOTO: {
695 flag.enabled(!cmd.argument().empty()
696 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
700 case LFUN_CHANGES_TRACK:
702 flag.setOnOff(buffer_->params().trackChanges);
705 case LFUN_CHANGES_OUTPUT:
706 flag.enabled(buffer_);
707 flag.setOnOff(buffer_->params().outputChanges);
710 case LFUN_CHANGES_MERGE:
711 case LFUN_CHANGE_NEXT:
712 case LFUN_ALL_CHANGES_ACCEPT:
713 case LFUN_ALL_CHANGES_REJECT:
714 // TODO: context-sensitive enabling of LFUNs
715 // In principle, these command should only be enabled if there
716 // is a change in the document. However, without proper
717 // optimizations, this will inevitably result in poor performance.
718 flag.enabled(buffer_);
721 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
722 flag.setOnOff(buffer_->params().compressed);
734 Update::flags BufferView::dispatch(FuncRequest const & cmd)
736 //lyxerr << BOOST_CURRENT_FUNCTION
737 // << [ cmd = " << cmd << "]" << endl;
739 // Make sure that the cached BufferView is correct.
740 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
741 << " action[" << cmd.action << ']'
742 << " arg[" << to_utf8(cmd.argument()) << ']'
743 << " x[" << cmd.x << ']'
744 << " y[" << cmd.y << ']'
745 << " button[" << cmd.button() << ']'
748 // FIXME: this should not be possible.
752 Cursor & cur = cursor_;
753 // Default Update flags.
754 Update::flags updateFlags = Update::Force | Update::FitCursor;
756 switch (cmd.action) {
759 cur.message(_("Undo"));
760 cur.clearSelection();
761 if (!textUndo(*this)) {
762 cur.message(_("No further undo information"));
763 updateFlags = Update::None;
768 cur.message(_("Redo"));
769 cur.clearSelection();
770 if (!textRedo(*this)) {
771 cur.message(_("No further redo information"));
772 updateFlags = Update::None;
776 case LFUN_FILE_INSERT:
778 menuInsertLyXFile(to_utf8(cmd.argument()));
781 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
783 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
786 case LFUN_FILE_INSERT_PLAINTEXT:
788 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
791 case LFUN_FONT_STATE:
792 cur.message(cur.currentState());
795 case LFUN_BOOKMARK_SAVE:
796 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
799 case LFUN_LABEL_GOTO: {
800 docstring label = cmd.argument();
803 getInsetByCode<InsetRef>(cursor_,
806 label = inset->getParam("reference");
807 // persistent=false: use temp_bookmark
817 case LFUN_PARAGRAPH_GOTO: {
818 int const id = convert<int>(to_utf8(cmd.argument()));
820 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
821 ParIterator par = b->getParFromID(id);
822 if (par == b->par_iterator_end()) {
824 << "No matching paragraph found! ["
825 << id << "]." << endl;
828 << "Paragraph " << par->id()
829 << " found in buffer `"
830 << b->fileName() << "'." << endl;
834 setCursor(makeDocIterator(par, 0));
836 // Switch to other buffer view and resend cmd
837 theLyXFunc().dispatch(FuncRequest(
838 LFUN_BUFFER_SWITCH, b->fileName()));
839 theLyXFunc().dispatch(cmd);
840 updateFlags = Update::None;
849 case LFUN_OUTLINE_UP:
850 toc::outline(toc::Up, cursor_);
851 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
852 updateLabels(*buffer_);
854 case LFUN_OUTLINE_DOWN:
855 toc::outline(toc::Down, cursor_);
856 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
857 updateLabels(*buffer_);
859 case LFUN_OUTLINE_IN:
860 toc::outline(toc::In, cursor_);
861 updateLabels(*buffer_);
863 case LFUN_OUTLINE_OUT:
864 toc::outline(toc::Out, cursor_);
865 updateLabels(*buffer_);
869 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
872 case LFUN_REFERENCE_NEXT: {
873 vector<Inset_code> tmp;
874 tmp.push_back(Inset::LABEL_CODE);
875 tmp.push_back(Inset::REF_CODE);
876 bv_funcs::gotoInset(this, tmp, true);
880 case LFUN_CHANGES_TRACK:
881 buffer_->params().trackChanges = !buffer_->params().trackChanges;
884 case LFUN_CHANGES_OUTPUT:
885 buffer_->params().outputChanges = !buffer_->params().outputChanges;
886 if (buffer_->params().outputChanges) {
887 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
888 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
889 LaTeXFeatures::isAvailable("xcolor");
891 if (!dvipost && !xcolorsoul) {
892 Alert::warning(_("Changes not shown in LaTeX output"),
893 _("Changes will not be highlighted in LaTeX output, "
894 "because neither dvipost nor xcolor/soul are installed.\n"
895 "Please install these packages or redefine "
896 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
897 } else if (!xcolorsoul) {
898 Alert::warning(_("Changes not shown in LaTeX output"),
899 _("Changes will not be highlighted in LaTeX output "
900 "when using pdflatex, because xcolor and soul are not installed.\n"
901 "Please install both packages or redefine "
902 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
907 case LFUN_CHANGE_NEXT:
908 findNextChange(this);
911 case LFUN_CHANGES_MERGE:
912 if (findNextChange(this))
913 showDialog("changes");
916 case LFUN_ALL_CHANGES_ACCEPT:
917 // select complete document
918 cursor_.reset(buffer_->inset());
919 cursor_.selHandle(true);
920 buffer_->text().cursorBottom(cursor_);
921 // accept everything in a single step to support atomic undo
922 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
925 case LFUN_ALL_CHANGES_REJECT:
926 // select complete document
927 cursor_.reset(buffer_->inset());
928 cursor_.selHandle(true);
929 buffer_->text().cursorBottom(cursor_);
930 // reject everything in a single step to support atomic undo
931 // Note: reject does not work recursively; the user may have to repeat the operation
932 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
939 case LFUN_WORD_REPLACE:
944 cur.clearSelection();
946 cur.message(from_utf8(N_("Mark off")));
950 cur.clearSelection();
953 cur.message(from_utf8(N_("Mark on")));
956 case LFUN_MARK_TOGGLE:
957 cur.clearSelection();
960 cur.message(from_utf8(N_("Mark removed")));
963 cur.message(from_utf8(N_("Mark set")));
968 case LFUN_SCREEN_RECENTER:
972 case LFUN_BIBTEX_DATABASE_ADD: {
973 Cursor tmpcur = cursor_;
974 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
975 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
978 if (inset->addDatabase(to_utf8(cmd.argument())))
979 buffer_->updateBibfilesCache();
984 case LFUN_BIBTEX_DATABASE_DEL: {
985 Cursor tmpcur = cursor_;
986 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
987 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
990 if (inset->delDatabase(to_utf8(cmd.argument())))
991 buffer_->updateBibfilesCache();
996 case LFUN_WORDS_COUNT: {
997 DocIterator from, to;
998 if (cur.selection()) {
999 from = cur.selectionBegin();
1000 to = cur.selectionEnd();
1002 from = doc_iterator_begin(buffer_->inset());
1003 to = doc_iterator_end(buffer_->inset());
1005 int const count = countWords(from, to);
1008 if (cur.selection())
1009 message = bformat(_("%1$d words in selection."),
1012 message = bformat(_("%1$d words in document."),
1016 if (cur.selection())
1017 message = _("One word in selection.");
1019 message = _("One word in document.");
1022 Alert::information(_("Count words"), message);
1026 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1027 // turn compression on/off
1028 buffer_->params().compressed = !buffer_->params().compressed;
1031 case LFUN_NEXT_INSET_TOGGLE: {
1032 // this is the real function we want to invoke
1033 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1034 // if there is an inset at cursor, see whether it
1036 Inset * inset = cur.nextInset();
1037 if (inset && inset->isActive()) {
1038 Cursor tmpcur = cur;
1039 tmpcur.pushLeft(*inset);
1040 inset->dispatch(tmpcur, tmpcmd);
1041 if (tmpcur.result().dispatched()) {
1045 // if it did not work, try the underlying inset.
1046 if (!cur.result().dispatched())
1047 cur.dispatch(tmpcmd);
1049 if (cur.result().dispatched())
1050 cur.clearSelection();
1056 updateFlags = Update::None;
1063 docstring const BufferView::requestSelection()
1068 Cursor & cur = cursor_;
1070 if (!cur.selection()) {
1071 xsel_cache_.set = false;
1075 if (!xsel_cache_.set ||
1076 cur.top() != xsel_cache_.cursor ||
1077 cur.anchor_.top() != xsel_cache_.anchor)
1079 xsel_cache_.cursor = cur.top();
1080 xsel_cache_.anchor = cur.anchor_.top();
1081 xsel_cache_.set = cur.selection();
1082 return cur.selectionAsString(false);
1088 void BufferView::clearSelection()
1091 cursor_.clearSelection();
1092 // Clear the selection buffer. Otherwise a subsequent
1093 // middle-mouse-button paste would use the selection buffer,
1094 // not the more current external selection.
1095 cap::clearSelection();
1096 xsel_cache_.set = false;
1097 // The buffer did not really change, but this causes the
1098 // redraw we need because we cleared the selection above.
1104 void BufferView::workAreaResize(int width, int height)
1106 // Update from work area
1110 // The complete text metrics will be redone.
1111 text_metrics_.clear();
1118 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1120 pit_type pit = text.getPitNearY(*this, y);
1121 BOOST_ASSERT(pit != -1);
1122 Paragraph const & par = text.getPar(pit);
1124 LYXERR(Debug::DEBUG)
1125 << BOOST_CURRENT_FUNCTION
1130 InsetList::const_iterator iit = par.insetlist.begin();
1131 InsetList::const_iterator iend = par.insetlist.end();
1132 for (; iit != iend; ++iit) {
1133 Inset * const inset = iit->inset;
1134 if (inset->covers(*this, x, y)) {
1135 if (!inset->descendable())
1136 // No need to go further down if the inset is not
1140 size_t cell_number = inset->nargs();
1141 // Check all the inner cell.
1142 for (size_t i = 0; i != cell_number; ++i) {
1143 Text const * inner_text = inset->getText(i);
1146 Inset const * inset_deeper =
1147 getCoveringInset(*inner_text, x, y);
1149 return inset_deeper;
1153 LYXERR(Debug::DEBUG)
1154 << BOOST_CURRENT_FUNCTION
1155 << ": Hit inset: " << inset << endl;
1159 LYXERR(Debug::DEBUG)
1160 << BOOST_CURRENT_FUNCTION
1161 << ": No inset hit. " << endl;
1166 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1168 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1170 // This is only called for mouse related events including
1171 // LFUN_FILE_OPEN generated by drag-and-drop.
1172 FuncRequest cmd = cmd0;
1174 // E.g. Qt mouse press when no buffer
1179 cur.push(buffer_->inset());
1180 cur.selection() = cursor_.selection();
1182 // Either the inset under the cursor or the
1183 // surrounding Text will handle this event.
1185 // make sure we stay within the screen...
1186 cmd.y = min(max(cmd.y, -1), height_);
1188 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1190 // Get inset under mouse, if there is one.
1191 Inset const * covering_inset =
1192 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1193 if (covering_inset == last_inset_)
1194 // Same inset, no need to do anything...
1197 bool need_redraw = false;
1198 // const_cast because of setMouseHover().
1199 Inset * inset = const_cast<Inset *>(covering_inset);
1201 // Remove the hint on the last hovered inset (if any).
1202 need_redraw |= last_inset_->setMouseHover(false);
1204 // Highlighted the newly hovered inset (if any).
1205 need_redraw |= inset->setMouseHover(true);
1206 last_inset_ = inset;
1208 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1209 // not expose the button for redraw. We adjust here the metrics dimension
1210 // to enable a full redraw.
1211 // FIXME: It is possible to redraw only the area around the button!
1213 && metrics_info_.update_strategy == SingleParUpdate) {
1214 // FIXME: It should be possible to redraw only the area around
1215 // the button by doing this:
1217 //metrics_info_.singlepar = false;
1218 //metrics_info_.y1 = ymin of button;
1219 //metrics_info_.y2 = ymax of button;
1221 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1222 // between background updates and text updates. So we use the hammer
1223 // solution for now. We could also avoid the updateMetrics() below
1224 // by using the first and last pit of the CoordCache. Have a look
1225 // at Text::getPitNearY() to see what I mean.
1227 //metrics_info_.pit1 = first pit of CoordCache;
1228 //metrics_info_.pit2 = last pit of CoordCache;
1229 //metrics_info_.singlepar = false;
1230 //metrics_info_.y1 = 0;
1231 //metrics_info_.y2 = height_;
1233 updateMetrics(false);
1236 // This event (moving without mouse click) is not passed further.
1237 // This should be changed if it is further utilized.
1241 // Build temporary cursor.
1242 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1244 // Put anchor at the same position.
1247 // Try to dispatch to an non-editable inset near this position
1248 // via the temp cursor. If the inset wishes to change the real
1249 // cursor it has to do so explicitly by using
1250 // cur.bv().cursor() = cur; (or similar)
1252 inset->dispatch(cur, cmd);
1255 // Now dispatch to the temporary cursor. If the real cursor should
1256 // be modified, the inset's dispatch has to do so explicitly.
1257 if (!cur.result().dispatched())
1260 // Redraw if requested and necessary.
1261 if (cur.result().dispatched() && cur.result().update())
1262 return update(cur.result().update());
1268 void BufferView::scroll(int /*lines*/)
1273 // Text const * t = &buffer_->text();
1274 // int const line_height = defaultRowHeight();
1276 // // The new absolute coordinate
1277 // int new_top_y = top_y() + lines * line_height;
1279 // // Restrict to a valid value
1280 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1281 // new_top_y = std::max(0, new_top_y);
1283 // scrollDocView(new_top_y);
1288 void BufferView::setCursorFromRow(int row)
1293 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1296 buffer_->text().setCursor(cursor_, 0, 0);
1298 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1302 void BufferView::gotoLabel(docstring const & label)
1304 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1305 vector<docstring> labels;
1306 it->getLabelList(*buffer_, labels);
1307 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1316 TextMetrics const & BufferView::textMetrics(Text const * t) const
1318 return const_cast<BufferView *>(this)->textMetrics(t);
1322 TextMetrics & BufferView::textMetrics(Text const * t)
1324 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1325 if (tmc_it == text_metrics_.end()) {
1326 tmc_it = text_metrics_.insert(
1327 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1329 return tmc_it->second;
1333 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1336 return textMetrics(t).parMetrics(pit);
1340 int BufferView::workHeight() const
1346 void BufferView::setCursor(DocIterator const & dit)
1348 size_t const n = dit.depth();
1349 for (size_t i = 0; i < n; ++i)
1350 dit[i].inset().edit(cursor_, true);
1352 cursor_.setCursor(dit);
1353 cursor_.selection() = false;
1357 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1359 // Would be wrong to delete anything if we have a selection.
1360 if (cur.selection())
1363 bool need_anchor_change = false;
1364 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1365 need_anchor_change);
1367 if (need_anchor_change)
1373 updateLabels(*buffer_);
1375 updateMetrics(false);
1381 bool BufferView::mouseSetCursor(Cursor & cur)
1383 BOOST_ASSERT(&cur.bv() == this);
1385 // Has the cursor just left the inset?
1386 bool badcursor = false;
1387 bool leftinset = (&cursor_.inset() != &cur.inset());
1389 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1391 // do the dEPM magic if needed
1392 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1393 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1394 // the leftinset bool would not be necessary (badcursor instead).
1395 bool update = leftinset;
1396 if (!badcursor && cursor_.inTexted())
1397 update |= checkDepm(cur, cursor_);
1399 // if the cursor was in an empty script inset and the new
1400 // position is in the nucleus of the inset, notifyCursorLeaves
1401 // will kill the script inset itself. So we check all the
1402 // elements of the cursor to make sure that they are correct.
1403 // For an example, see bug 2933:
1404 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1405 // The code below could maybe be moved to a DocIterator method.
1406 //lyxerr << "cur before " << cur <<std::endl;
1407 DocIterator dit(cur.inset());
1408 dit.push_back(cur.bottom());
1410 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1411 dit.push_back(cur[i]);
1414 //lyxerr << "5 cur after" << dit <<std::endl;
1416 cursor_.setCursor(dit);
1417 cursor_.boundary(cur.boundary());
1418 cursor_.clearSelection();
1424 void BufferView::putSelectionAt(DocIterator const & cur,
1425 int length, bool backwards)
1427 cursor_.clearSelection();
1433 cursor_.pos() += length;
1434 cursor_.setSelection(cursor_, -length);
1436 cursor_.setSelection(cursor_, length);
1437 cap::saveSelection(cursor_);
1442 Cursor & BufferView::cursor()
1448 Cursor const & BufferView::cursor() const
1454 pit_type BufferView::anchor_ref() const
1460 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1462 return metrics_info_;
1466 // FIXME: We should split-up updateMetrics() for the singlepar case.
1467 void BufferView::updateMetrics(bool singlepar)
1469 Text & buftext = buffer_->text();
1470 TextMetrics & tm = textMetrics(&buftext);
1471 pit_type size = int(buftext.paragraphs().size());
1473 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1474 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1478 // If the paragraph metrics has changed, we can not
1479 // use the singlepar optimisation.
1481 // In Single Paragraph mode, rebreak only
1482 // the (main text, not inset!) paragraph containing the cursor.
1483 // (if this paragraph contains insets etc., rebreaking will
1484 // recursively descend)
1485 && tm.redoParagraph(cursor_.bottom().pit()))
1488 pit_type const pit = anchor_ref_;
1491 size_t const npit = buftext.paragraphs().size();
1493 // Rebreak anchor paragraph.
1495 tm.redoParagraph(pit);
1497 // Clear out the position cache in case of full screen redraw.
1499 coord_cache_.clear();
1501 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1503 // Redo paragraphs above anchor if necessary.
1505 while (y1 > 0 && pit1 > 0) {
1506 y1 -= tm.parMetrics(pit1).ascent();
1509 tm.redoParagraph(pit1);
1510 y1 -= tm.parMetrics(pit1).descent();
1514 // Take care of ascent of first line
1515 y1 -= tm.parMetrics(pit1).ascent();
1517 // Normalize anchor for next time
1521 // Grey at the beginning is ugly
1522 if (pit1 == 0 && y1 > 0) {
1528 // Redo paragraphs below the anchor if necessary.
1530 while (y2 < height_ && pit2 < int(npit) - 1) {
1531 y2 += tm.parMetrics(pit2).descent();
1534 tm.redoParagraph(pit2);
1535 y2 += tm.parMetrics(pit2).ascent();
1538 // Take care of descent of last line
1539 y2 += tm.parMetrics(pit2).descent();
1541 // The coordinates of all these paragraphs are correct, cache them
1543 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1544 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1545 ParagraphMetrics const & pm = tm.parMetrics(pit);
1547 parPos[pit] = Point(0, y);
1548 if (singlepar && pit == cursor_.bottom().pit()) {
1549 // In Single Paragraph mode, collect here the
1550 // y1 and y2 of the (one) paragraph the cursor is in
1551 y1 = y - pm.ascent();
1552 y2 = y + pm.descent();
1558 // collect cursor paragraph iter bounds
1559 pit1 = cursor_.bottom().pit();
1560 pit2 = cursor_.bottom().pit();
1563 LYXERR(Debug::DEBUG)
1564 << BOOST_CURRENT_FUNCTION
1567 << " pit1: " << pit1
1568 << " pit2: " << pit2
1569 << " npit: " << npit
1570 << " singlepar: " << singlepar
1574 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1575 singlepar? SingleParUpdate: FullScreenUpdate, size);
1577 if (lyxerr.debugging(Debug::WORKAREA)) {
1578 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1579 coord_cache_.dump();
1584 void BufferView::menuInsertLyXFile(string const & filenm)
1586 BOOST_ASSERT(cursor_.inTexted());
1587 string filename = filenm;
1589 if (filename.empty()) {
1590 // Launch a file browser
1592 string initpath = lyxrc.document_path;
1595 string const trypath = buffer_->filePath();
1596 // If directory is writeable, use this as default.
1597 if (isDirWriteable(FileName(trypath)))
1602 FileDialog fileDlg(_("Select LyX document to insert"),
1604 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1605 make_pair(_("Examples|#E#e"),
1606 from_utf8(addPath(package().system_support().absFilename(),
1609 FileDialog::Result result =
1610 fileDlg.open(from_utf8(initpath),
1611 FileFilterList(_("LyX Documents (*.lyx)")),
1614 if (result.first == FileDialog::Later)
1618 filename = to_utf8(result.second);
1620 // check selected filename
1621 if (filename.empty()) {
1622 // emit message signal.
1623 message(_("Canceled."));
1628 // Get absolute path of file and add ".lyx"
1629 // to the filename if necessary
1630 filename = fileSearch(string(), filename, "lyx").absFilename();
1632 docstring const disp_fn = makeDisplayPath(filename);
1633 // emit message signal.
1634 message(bformat(_("Inserting document %1$s..."), disp_fn));
1637 Buffer buf("", false);
1638 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1639 ErrorList & el = buffer_->errorList("Parse");
1640 // Copy the inserted document error list into the current buffer one.
1641 el = buf.errorList("Parse");
1642 recordUndo(cursor_);
1643 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1644 buf.params().textclass, el);
1645 res = _("Document %1$s inserted.");
1647 res = _("Could not insert document %1$s");
1649 // emit message signal.
1650 message(bformat(res, disp_fn));
1651 buffer_->errors("Parse");