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"
19 #include "dociterator.h"
21 #include "errorlist.h"
23 #include "FloatList.h"
27 #include "lyxtextclass.h"
28 #include "paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "pariterator.h"
35 #include "TocBackend.h"
36 #include "vc-backend.h"
38 #include "frontends/Alert.h"
40 #include "insets/insetbibitem.h"
41 #include "insets/insetinclude.h"
43 #include "support/filetools.h"
44 #include "support/fs_extras.h"
45 #include "support/lyxlib.h"
47 #include <boost/bind.hpp>
48 #include <boost/filesystem/operations.hpp>
55 using support::bformat;
56 using support::FileName;
57 using support::libFileSearch;
58 using support::makeAbsPath;
59 using support::makeDisplayPath;
60 using support::onlyFilename;
61 using support::onlyPath;
62 using support::unlink;
67 namespace Alert = frontend::Alert;
68 namespace fs = boost::filesystem;
72 bool readFile(Buffer * const b, FileName const & s)
76 // File information about normal file
77 if (!fs::exists(s.toFilesystemEncoding())) {
78 docstring const file = makeDisplayPath(s.absFilename(), 50);
79 docstring text = bformat(_("The specified document\n%1$s"
80 "\ncould not be read."), file);
81 Alert::error(_("Could not read document"), text);
85 // Check if emergency save file exists and is newer.
86 FileName const e(s.absFilename() + ".emergency");
88 if (fs::exists(e.toFilesystemEncoding()) &&
89 fs::exists(s.toFilesystemEncoding()) &&
90 fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
92 docstring const file = makeDisplayPath(s.absFilename(), 20);
93 docstring const text =
94 bformat(_("An emergency save of the document "
96 "Recover emergency save?"), file);
97 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
98 _("&Recover"), _("&Load Original"),
102 // the file is not saved if we load the emergency file.
104 return b->readFile(e);
112 // Now check if autosave file is newer.
113 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
115 if (fs::exists(a.toFilesystemEncoding()) &&
116 fs::exists(s.toFilesystemEncoding()) &&
117 fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
119 docstring const file = makeDisplayPath(s.absFilename(), 20);
120 docstring const text =
121 bformat(_("The backup of the document "
122 "%1$s is newer.\n\nLoad the "
123 "backup instead?"), file);
124 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
125 _("&Load backup"), _("Load &original"),
129 // the file is not saved if we load the autosave file.
131 return b->readFile(a);
133 // Here we delete the autosave
140 return b->readFile(s);
148 bool loadLyXFile(Buffer * b, FileName const & s)
152 if (fs::is_readable(s.toFilesystemEncoding())) {
153 if (readFile(b, s)) {
154 b->lyxvc().file_found_hook(s);
155 if (!fs::is_writable(s.toFilesystemEncoding()))
156 b->setReadonly(true);
160 docstring const file = makeDisplayPath(s.absFilename(), 20);
161 // Here we probably should run
162 if (LyXVC::file_not_found_hook(s)) {
163 docstring const text =
164 bformat(_("Do you want to retrieve the document"
165 " %1$s from version control?"), file);
166 int const ret = Alert::prompt(_("Retrieve from version control?"),
167 text, 0, 1, _("&Retrieve"), _("&Cancel"));
170 // How can we know _how_ to do the checkout?
171 // With the current VC support it has to be,
172 // a RCS file since CVS do not have special ,v files.
174 return loadLyXFile(b, s);
181 // FIXME newFile() should probably be a member method of Application...
182 Buffer * newFile(string const & filename, string const & templatename,
186 Buffer * b = theBufferList().newBuffer(filename);
190 // use defaults.lyx as a default template if it exists.
191 if (templatename.empty())
192 tname = libFileSearch("templates", "defaults.lyx");
194 tname = makeAbsPath(templatename);
196 if (!tname.empty()) {
197 if (!b->readFile(tname)) {
198 docstring const file = makeDisplayPath(tname.absFilename(), 50);
199 docstring const text = bformat(
200 _("The specified document template\n%1$s\ncould not be read."),
202 Alert::error(_("Could not read template"), text);
203 theBufferList().release(b);
210 b->setFileName(filename);
213 b->setReadonly(false);
214 b->fully_loaded(true);
215 b->updateDocLang(b->params().language);
221 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
222 ErrorList & errorList)
224 TeXErrors::Errors::const_iterator cit = terr.begin();
225 TeXErrors::Errors::const_iterator end = terr.end();
227 for (; cit != end; ++cit) {
230 int errorrow = cit->error_in_line;
231 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
237 found = buf.texrow().getIdFromRow(errorrow, id_end,
239 } while (found && id_start == id_end && pos_start == pos_end);
241 errorList.push_back(ErrorItem(cit->error_desc,
242 cit->error_text, id_start, pos_start, pos_end));
247 string const bufferFormat(Buffer const & buffer)
249 if (buffer.isDocBook())
251 else if (buffer.isLiterate())
258 int countWords(DocIterator const & from, DocIterator const & to)
262 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
263 // Copied and adapted from isLetter() in ControlSpellChecker
265 && dit.pos() != dit.lastpos()
266 && dit.paragraph().isLetter(dit.pos())
267 && !dit.paragraph().isDeleted(dit.pos())) {
282 depth_type getDepth(DocIterator const & it)
284 depth_type depth = 0;
285 for (size_t i = 0 ; i < it.depth() ; ++i)
286 if (!it[i].inset().inMathed())
287 depth += it[i].paragraph().getDepth() + 1;
288 // remove 1 since the outer inset does not count
292 depth_type getItemDepth(ParIterator const & it)
294 Paragraph const & par = *it;
295 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
297 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
300 // this will hold the lowest depth encountered up to now.
301 depth_type min_depth = getDepth(it);
302 ParIterator prev_it = it;
305 --prev_it.top().pit();
307 // start of nested inset: go to outer par
309 if (prev_it.empty()) {
310 // start of document: nothing to do
315 // We search for the first paragraph with same label
316 // that is not more deeply nested.
317 Paragraph & prev_par = *prev_it;
318 depth_type const prev_depth = getDepth(prev_it);
319 if (labeltype == prev_par.layout()->labeltype) {
320 if (prev_depth < min_depth) {
321 return prev_par.itemdepth + 1;
323 else if (prev_depth == min_depth) {
324 return prev_par.itemdepth;
327 min_depth = std::min(min_depth, prev_depth);
328 // small optimization: if we are at depth 0, we won't
329 // find anything else
330 if (prev_depth == 0) {
337 bool needEnumCounterReset(ParIterator const & it)
339 Paragraph const & par = *it;
340 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
341 depth_type const cur_depth = par.getDepth();
342 ParIterator prev_it = it;
343 while (prev_it.pit()) {
344 --prev_it.top().pit();
345 Paragraph const & prev_par = *prev_it;
346 if (prev_par.getDepth() <= cur_depth)
347 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
349 // start of nested inset: reset
354 // set the label of a paragraph. This includes the counters.
355 void setLabel(Buffer const & buf, ParIterator & it, LyXTextClass const & textclass)
357 Paragraph & par = *it;
358 LyXLayout_ptr const & layout = par.layout();
359 Counters & counters = textclass.counters();
362 par.params().appendix(par.params().startOfAppendix());
364 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
365 if (!par.params().appendix() &&
366 par.params().startOfAppendix()) {
367 par.params().appendix(true);
368 textclass.counters().reset();
372 // Compute the item depth of the paragraph
373 par.itemdepth = getItemDepth(it);
375 // erase what was there before
376 par.params().labelString(docstring());
378 if (layout->margintype == MARGIN_MANUAL) {
379 if (par.params().labelWidthString().empty())
380 par.setLabelWidthString(buf.translateLabel(layout->labelstring()));
382 par.setLabelWidthString(docstring());
385 // is it a layout that has an automatic label?
386 if (layout->labeltype == LABEL_COUNTER) {
387 if (layout->toclevel <= buf.params().secnumdepth
388 && (layout->latextype != LATEX_ENVIRONMENT
389 || isFirstInSequence(it.pit(), it.plist()))) {
390 counters.step(layout->counter);
391 docstring label = expandLabel(buf, layout,
392 par.params().appendix());
393 par.params().labelString(label);
395 } else if (layout->labeltype == LABEL_ITEMIZE) {
396 // At some point of time we should do something more
397 // clever here, like:
398 // par.params().labelString(
399 // buf.params().user_defined_bullet(par.itemdepth).getText());
400 // for now, use a simple hardcoded label
402 switch (par.itemdepth) {
404 itemlabel = char_type(0x2022);
407 itemlabel = char_type(0x2013);
410 itemlabel = char_type(0x2217);
413 itemlabel += char_type(0x2219); // or 0x00b7
417 par.params().labelString(itemlabel);
418 } else if (layout->labeltype == LABEL_ENUMERATE) {
420 // Yes I know this is a really, really! bad solution
422 docstring enumcounter = from_ascii("enum");
424 switch (par.itemdepth) {
436 // not a valid enumdepth...
440 // Maybe we have to reset the enumeration counter.
441 if (needEnumCounterReset(it))
442 counters.reset(enumcounter);
444 counters.step(enumcounter);
448 switch (par.itemdepth) {
450 format = N_("\\arabic{enumi}.");
453 format = N_("(\\alph{enumii})");
456 format = N_("\\roman{enumiii}.");
459 format = N_("\\Alph{enumiv}.");
462 // not a valid enumdepth...
466 par.params().labelString(counters.counterLabel(buf.B_(format)));
467 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
468 counters.step(from_ascii("bibitem"));
469 int number = counters.value(from_ascii("bibitem"));
471 par.bibitem()->setCounter(number);
472 par.params().labelString(buf.translateLabel(layout->labelstring()));
473 // In biblio should't be following counters but...
474 } else if (layout->labeltype == LABEL_SENSITIVE) {
475 // Search for the first float or wrap inset in the iterator
477 size_t i = it.depth();
480 InsetBase * const in = &it[i].inset();
481 if (in->lyxCode() == InsetBase::FLOAT_CODE
482 || in->lyxCode() == InsetBase::WRAP_CODE) {
483 type = in->getInsetName();
490 Floating const & fl = textclass.floats().getType(to_ascii(type));
492 counters.step(from_ascii(fl.type()));
494 // Doesn't work... yet.
495 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
497 // par->SetLayout(0);
498 s = buf.translateLabel(layout->labelstring());
501 par.params().labelString(s);
502 } else if (layout->labeltype == LABEL_NO_LABEL)
503 par.params().labelString(docstring());
505 par.params().labelString(buf.translateLabel(layout->labelstring()));
511 bool updateCurrentLabel(Buffer const & buf,
514 if (it == par_iterator_end(buf.inset()))
517 // if (it.lastpit == 0 && LyXText::isMainText(buf))
520 switch (it->layout()->labeltype) {
525 case LABEL_TOP_ENVIRONMENT:
526 case LABEL_CENTERED_TOP_ENVIRONMENT:
529 setLabel(buf, it, buf.params().getLyXTextClass());
532 case LABEL_SENSITIVE:
534 // do more things with enumerate later
535 case LABEL_ENUMERATE:
539 // This is dead code which get rid of a warning:
544 void updateLabels(Buffer const & buf,
545 ParIterator & from, ParIterator & to, bool childonly)
547 for (ParIterator it = from; it != to; ++it) {
548 if (it.pit() > it.lastpit())
550 if (!updateCurrentLabel (buf, it)) {
551 updateLabels(buf, childonly);
558 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
560 if (updateCurrentLabel(buf, iter))
563 updateLabels(buf, childonly);
567 void updateLabels(Buffer const & buf, bool childonly)
569 // Use the master text class also for child documents
570 LyXTextClass const & textclass = buf.params().getLyXTextClass();
573 // If this is a child document start with the master
574 Buffer const * const master = buf.getMasterBuffer();
575 if (master != &buf) {
576 updateLabels(*master);
580 // start over the counters
581 textclass.counters().reset();
584 ParIterator const end = par_iterator_end(buf.inset());
586 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
587 // reduce depth if necessary
589 Paragraph const & prevpar = it.plist()[it.pit() - 1];
590 it->params().depth(min(it->params().depth(),
591 prevpar.getMaxDepthAfter()));
593 it->params().depth(0);
595 // set the counter for this paragraph
596 setLabel(buf, it, textclass);
599 InsetList::const_iterator iit = it->insetlist.begin();
600 InsetList::const_iterator end = it->insetlist.end();
601 for (; iit != end; ++iit) {
602 if (iit->inset->lyxCode() == InsetBase::INCLUDE_CODE)
603 static_cast<InsetInclude const *>(iit->inset)
608 const_cast<Buffer &>(buf).tocBackend().update();
612 docstring expandLabel(Buffer const & buf,
613 LyXLayout_ptr const & layout, bool appendix)
615 LyXTextClass const & tclass = buf.params().getLyXTextClass();
617 docstring fmt = buf.translateLabel(appendix ?
618 layout->labelstring_appendix() :
619 layout->labelstring());
621 // handle 'inherited level parts' in 'fmt',
622 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
623 size_t const i = fmt.find('@', 0);
624 if (i != docstring::npos) {
625 size_t const j = fmt.find('@', i + 1);
626 if (j != docstring::npos) {
627 docstring parent(fmt, i + 1, j - i - 1);
629 docstring label = expandLabel(buf, tclass[to_utf8(parent)], appendix);
630 fmt = docstring(fmt, 0, i) + label + docstring(fmt, j + 1, docstring::npos);
634 return tclass.counters().counterLabel(fmt);