2 * \file buffer_funcs.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Alfredo Braunstein
9 * Full author contact details are available in file CREDITS.
15 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
20 #include "DocIterator.h"
22 #include "ErrorList.h"
24 #include "FloatList.h"
26 #include "InsetIterator.h"
30 #include "TextClass.h"
31 #include "Paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "ParagraphList.h"
34 #include "ParagraphParameters.h"
35 #include "ParIterator.h"
38 #include "TocBackend.h"
39 #include "VCBackend.h"
41 #include "frontends/alert.h"
43 #include "insets/InsetBibitem.h"
44 #include "insets/InsetCaption.h"
45 #include "insets/InsetInclude.h"
46 #include "insets/InsetTabular.h"
48 #include "support/convert.h"
49 #include "support/filetools.h"
50 #include "support/fs_extras.h"
51 #include "support/lyxlib.h"
53 #include <boost/bind.hpp>
54 #include <boost/filesystem/operations.hpp>
64 using support::bformat;
65 using support::FileName;
66 using support::libFileSearch;
67 using support::makeAbsPath;
68 using support::makeDisplayPath;
69 using support::onlyFilename;
70 using support::onlyPath;
71 using support::unlink;
73 namespace Alert = frontend::Alert;
74 namespace fs = boost::filesystem;
78 bool readFile(Buffer * const b, FileName const & s)
82 // File information about normal file
83 if (!fs::exists(s.toFilesystemEncoding())) {
84 docstring const file = makeDisplayPath(s.absFilename(), 50);
85 docstring text = bformat(_("The specified document\n%1$s"
86 "\ncould not be read."), file);
87 Alert::error(_("Could not read document"), text);
91 // Check if emergency save file exists and is newer.
92 FileName const e(s.absFilename() + ".emergency");
94 if (fs::exists(e.toFilesystemEncoding()) &&
95 fs::exists(s.toFilesystemEncoding()) &&
96 fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
98 docstring const file = makeDisplayPath(s.absFilename(), 20);
99 docstring const text =
100 bformat(_("An emergency save of the document "
102 "Recover emergency save?"), file);
103 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
104 _("&Recover"), _("&Load Original"),
108 // the file is not saved if we load the emergency file.
110 return b->readFile(e);
118 // Now check if autosave file is newer.
119 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
121 if (fs::exists(a.toFilesystemEncoding()) &&
122 fs::exists(s.toFilesystemEncoding()) &&
123 fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
125 docstring const file = makeDisplayPath(s.absFilename(), 20);
126 docstring const text =
127 bformat(_("The backup of the document "
128 "%1$s is newer.\n\nLoad the "
129 "backup instead?"), file);
130 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
131 _("&Load backup"), _("Load &original"),
135 // the file is not saved if we load the autosave file.
137 return b->readFile(a);
139 // Here we delete the autosave
146 return b->readFile(s);
154 bool loadLyXFile(Buffer * b, FileName const & s)
158 if (fs::is_readable(s.toFilesystemEncoding())) {
159 if (readFile(b, s)) {
160 b->lyxvc().file_found_hook(s);
161 if (!fs::is_writable(s.toFilesystemEncoding()))
162 b->setReadonly(true);
166 docstring const file = makeDisplayPath(s.absFilename(), 20);
167 // Here we probably should run
168 if (LyXVC::file_not_found_hook(s)) {
169 docstring const text =
170 bformat(_("Do you want to retrieve the document"
171 " %1$s from version control?"), file);
172 int const ret = Alert::prompt(_("Retrieve from version control?"),
173 text, 0, 1, _("&Retrieve"), _("&Cancel"));
176 // How can we know _how_ to do the checkout?
177 // With the current VC support it has to be,
178 // a RCS file since CVS do not have special ,v files.
180 return loadLyXFile(b, s);
188 bool checkIfLoaded(FileName const & fn)
190 return theBufferList().getBuffer(fn.absFilename());
194 Buffer * checkAndLoadLyXFile(FileName const & filename)
196 // File already open?
197 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
199 if (checkBuffer->isClean())
201 docstring const file = makeDisplayPath(filename.absFilename(), 20);
202 docstring text = bformat(_(
203 "The document %1$s is already loaded and has unsaved changes.\n"
204 "Do you want to abandon your changes and reload the version on disk?"), file);
205 if (Alert::prompt(_("Reload saved document?"),
206 text, 0, 1, _("&Reload"), _("&Keep Changes")))
209 // FIXME: should be LFUN_REVERT
210 if (theBufferList().close(checkBuffer, false))
212 return checkAndLoadLyXFile(filename);
214 // The file could not be closed.
218 if (isFileReadable(filename)) {
219 Buffer * b = theBufferList().newBuffer(filename.absFilename());
220 if (!lyx::loadLyXFile(b, filename)) {
221 theBufferList().release(b);
227 docstring text = bformat(_("The document %1$s does not yet "
228 "exist.\n\nDo you want to create a new document?"),
229 from_utf8(filename.absFilename()));
230 if (!Alert::prompt(_("Create new document?"),
231 text, 0, 1, _("&Create"), _("Cancel")))
232 return newFile(filename.absFilename(), string(), true);
237 // FIXME newFile() should probably be a member method of Application...
238 Buffer * newFile(string const & filename, string const & templatename,
242 Buffer * b = theBufferList().newBuffer(filename);
246 // use defaults.lyx as a default template if it exists.
247 if (templatename.empty())
248 tname = libFileSearch("templates", "defaults.lyx");
250 tname = makeAbsPath(templatename);
252 if (!tname.empty()) {
253 if (!b->readFile(tname)) {
254 docstring const file = makeDisplayPath(tname.absFilename(), 50);
255 docstring const text = bformat(
256 _("The specified document template\n%1$s\ncould not be read."),
258 Alert::error(_("Could not read template"), text);
259 theBufferList().release(b);
266 b->setFileName(filename);
269 b->setReadonly(false);
270 b->fully_loaded(true);
276 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
277 ErrorList & errorList)
279 TeXErrors::Errors::const_iterator cit = terr.begin();
280 TeXErrors::Errors::const_iterator end = terr.end();
282 for (; cit != end; ++cit) {
285 int errorrow = cit->error_in_line;
286 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
292 found = buf.texrow().getIdFromRow(errorrow, id_end,
294 } while (found && id_start == id_end && pos_start == pos_end);
296 errorList.push_back(ErrorItem(cit->error_desc,
297 cit->error_text, id_start, pos_start, pos_end));
302 string const bufferFormat(Buffer const & buffer)
304 if (buffer.isDocBook())
306 else if (buffer.isLiterate())
313 int countWords(DocIterator const & from, DocIterator const & to)
317 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
318 // Copied and adapted from isLetter() in ControlSpellChecker
320 && dit.pos() != dit.lastpos()
321 && dit.paragraph().isLetter(dit.pos())
322 && !dit.paragraph().isDeleted(dit.pos())) {
337 depth_type getDepth(DocIterator const & it)
339 depth_type depth = 0;
340 for (size_t i = 0 ; i < it.depth() ; ++i)
341 if (!it[i].inset().inMathed())
342 depth += it[i].paragraph().getDepth() + 1;
343 // remove 1 since the outer inset does not count
347 depth_type getItemDepth(ParIterator const & it)
349 Paragraph const & par = *it;
350 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
352 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
355 // this will hold the lowest depth encountered up to now.
356 depth_type min_depth = getDepth(it);
357 ParIterator prev_it = it;
360 --prev_it.top().pit();
362 // start of nested inset: go to outer par
364 if (prev_it.empty()) {
365 // start of document: nothing to do
370 // We search for the first paragraph with same label
371 // that is not more deeply nested.
372 Paragraph & prev_par = *prev_it;
373 depth_type const prev_depth = getDepth(prev_it);
374 if (labeltype == prev_par.layout()->labeltype) {
375 if (prev_depth < min_depth) {
376 return prev_par.itemdepth + 1;
378 else if (prev_depth == min_depth) {
379 return prev_par.itemdepth;
382 min_depth = std::min(min_depth, prev_depth);
383 // small optimization: if we are at depth 0, we won't
384 // find anything else
385 if (prev_depth == 0) {
392 bool needEnumCounterReset(ParIterator const & it)
394 Paragraph const & par = *it;
395 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
396 depth_type const cur_depth = par.getDepth();
397 ParIterator prev_it = it;
398 while (prev_it.pit()) {
399 --prev_it.top().pit();
400 Paragraph const & prev_par = *prev_it;
401 if (prev_par.getDepth() <= cur_depth)
402 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
404 // start of nested inset: reset
409 // set the label of a paragraph. This includes the counters.
410 void setLabel(Buffer const & buf, ParIterator & it)
412 TextClass const & textclass = buf.params().getTextClass();
413 Paragraph & par = it.paragraph();
414 Layout_ptr const & layout = par.layout();
415 Counters & counters = textclass.counters();
417 if (par.params().startOfAppendix()) {
418 // FIXME: only the counter corresponding to toplevel
419 // sectionning should be reset
421 counters.appendix(true);
423 par.params().appendix(counters.appendix());
425 // Compute the item depth of the paragraph
426 par.itemdepth = getItemDepth(it);
428 if (layout->margintype == MARGIN_MANUAL) {
429 if (par.params().labelWidthString().empty())
430 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
432 par.params().labelWidthString(docstring());
435 // is it a layout that has an automatic label?
436 if (layout->labeltype == LABEL_COUNTER) {
437 if (layout->toclevel <= buf.params().secnumdepth
438 && (layout->latextype != LATEX_ENVIRONMENT
439 || isFirstInSequence(it.pit(), it.plist()))) {
440 counters.step(layout->counter);
441 par.params().labelString(
442 par.expandLabel(layout, buf.params()));
444 par.params().labelString(docstring());
446 } else if (layout->labeltype == LABEL_ITEMIZE) {
447 // At some point of time we should do something more
448 // clever here, like:
449 // par.params().labelString(
450 // buf.params().user_defined_bullet(par.itemdepth).getText());
451 // for now, use a simple hardcoded label
453 switch (par.itemdepth) {
455 itemlabel = char_type(0x2022);
458 itemlabel = char_type(0x2013);
461 itemlabel = char_type(0x2217);
464 itemlabel = char_type(0x2219); // or 0x00b7
467 par.params().labelString(itemlabel);
469 } else if (layout->labeltype == LABEL_ENUMERATE) {
471 // Yes I know this is a really, really! bad solution
473 docstring enumcounter = from_ascii("enum");
475 switch (par.itemdepth) {
487 // not a valid enumdepth...
491 // Maybe we have to reset the enumeration counter.
492 if (needEnumCounterReset(it))
493 counters.reset(enumcounter);
495 counters.step(enumcounter);
499 switch (par.itemdepth) {
501 format = N_("\\arabic{enumi}.");
504 format = N_("(\\alph{enumii})");
507 format = N_("\\roman{enumiii}.");
510 format = N_("\\Alph{enumiv}.");
513 // not a valid enumdepth...
517 par.params().labelString(counters.counterLabel(
518 par.translateIfPossible(from_ascii(format), buf.params())));
520 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
521 counters.step(from_ascii("bibitem"));
522 int number = counters.value(from_ascii("bibitem"));
524 par.bibitem()->setCounter(number);
526 par.params().labelString(
527 par.translateIfPossible(layout->labelstring(), buf.params()));
528 // In biblio shouldn't be following counters but...
529 } else if (layout->labeltype == LABEL_SENSITIVE) {
530 string const & type = counters.current_float();
531 docstring full_label;
533 full_label = buf.B_("Senseless!!! ");
535 docstring name = buf.B_(textclass.floats().getType(type).name());
536 if (counters.hasCounter(from_utf8(type))) {
537 counters.step(from_utf8(type));
538 full_label = bformat(from_ascii("%1$s %2$s:"),
540 convert<docstring>(counters.value(from_utf8(type))));
542 full_label = bformat(from_ascii("%1$s #:"), name);
544 par.params().labelString(full_label);
546 } else if (layout->labeltype == LABEL_NO_LABEL)
547 par.params().labelString(docstring());
549 par.params().labelString(
550 par.translateIfPossible(layout->labelstring(), buf.params()));
555 void updateLabels(Buffer const & buf, ParIterator & parit)
557 BOOST_ASSERT(parit.pit() == 0);
559 depth_type maxdepth = 0;
560 pit_type const lastpit = parit.lastpit();
561 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
562 // reduce depth if necessary
563 parit->params().depth(min(parit->params().depth(), maxdepth));
564 maxdepth = parit->getMaxDepthAfter();
566 // set the counter for this paragraph
567 setLabel(buf, parit);
570 InsetList::const_iterator iit = parit->insetlist.begin();
571 InsetList::const_iterator end = parit->insetlist.end();
572 for (; iit != end; ++iit) {
573 parit.pos() = iit->pos;
574 iit->inset->updateLabels(buf, parit);
581 // FIXME: buf should should be const because updateLabels() modifies
582 // the contents of the paragraphs.
583 void updateLabels(Buffer const & buf, bool childonly)
585 Buffer const * const master = buf.getMasterBuffer();
586 // Use the master text class also for child documents
587 TextClass const & textclass = master->params().getTextClass();
590 // If this is a child document start with the master
591 if (master != &buf) {
592 updateLabels(*master);
596 // start over the counters
597 textclass.counters().reset();
600 Buffer & cbuf = const_cast<Buffer &>(buf);
602 if (buf.text().empty()) {
603 // FIXME: we don't call continue with updateLabels() here because
604 // it crashes on newly created documents. But the TocBackend needs to
605 // be initialised nonetheless so we update the tocBackend manually.
606 cbuf.tocBackend().update();
611 ParIterator parit = par_iterator_begin(buf.inset());
612 updateLabels(buf, parit);
614 cbuf.tocBackend().update();
616 cbuf.structureChanged();
620 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
622 if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
623 Buffer * master = buffer.getMasterBuffer();
624 master->tocBackend().updateItem(par_it);
625 master->structureChanged();
630 void loadChildDocuments(Buffer const & buf)
632 bool parse_error = false;
634 for (InsetIterator it = inset_iterator_begin(buf.inset()); it; ++it) {
635 if (it->lyxCode() != Inset::INCLUDE_CODE)
637 InsetInclude const & inset = static_cast<InsetInclude const &>(*it);
638 InsetCommandParams const & ip = inset.params();
639 Buffer * child = loadIfNeeded(buf, ip);
642 parse_error |= !child->errorList("Parse").empty();
643 loadChildDocuments(*child);
646 if (use_gui && buf.getMasterBuffer() == &buf)