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_fwd.h"
31 #include "ParagraphParameters.h"
32 #include "pariterator.h"
35 #include "vc-backend.h"
37 #include "frontends/Alert.h"
39 #include "insets/insetbibitem.h"
41 #include "support/filetools.h"
42 #include "support/fs_extras.h"
43 #include "support/lyxlib.h"
45 #include <boost/bind.hpp>
46 #include <boost/filesystem/operations.hpp>
49 using lyx::support::bformat;
50 using lyx::support::LibFileSearch;
51 using lyx::support::MakeDisplayPath;
52 using lyx::support::OnlyFilename;
53 using lyx::support::OnlyPath;
54 using lyx::support::unlink;
59 namespace fs = boost::filesystem;
61 extern BufferList bufferlist;
65 bool readFile(Buffer * const b, string const & s)
69 // File information about normal file
71 string const file = MakeDisplayPath(s, 50);
72 string text = bformat(_("The specified document\n%1$s"
73 "\ncould not be read."), file);
74 Alert::error(_("Could not read document"), text);
78 // Check if emergency save file exists and is newer.
79 string const e = OnlyPath(s) + OnlyFilename(s) + ".emergency";
81 if (fs::exists(e) && fs::exists(s)
82 && fs::last_write_time(e) > fs::last_write_time(s))
84 string const file = MakeDisplayPath(s, 20);
86 bformat(_("An emergency save of the document "
88 "Recover emergency save?"), file);
89 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
90 _("&Recover"), _("&Load Original"),
94 // the file is not saved if we load the emergency file.
96 return b->readFile(e);
104 // Now check if autosave file is newer.
105 string const a = OnlyPath(s) + '#' + OnlyFilename(s) + '#';
107 if (fs::exists(a) && fs::exists(s)
108 && fs::last_write_time(a) > fs::last_write_time(s))
110 string const file = MakeDisplayPath(s, 20);
112 bformat(_("The backup of the document "
113 "%1$s is newer.\n\nLoad the "
114 "backup instead?"), file);
115 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
116 _("&Load backup"), _("Load &original"),
120 // the file is not saved if we load the autosave file.
122 return b->readFile(a);
124 // Here we delete the autosave
131 return b->readFile(s);
139 bool loadLyXFile(Buffer * b, string const & s)
143 if (fs::is_readable(s)) {
144 if (readFile(b, s)) {
145 b->lyxvc().file_found_hook(s);
146 if (!fs::is_writable(s))
147 b->setReadonly(true);
151 string const file = MakeDisplayPath(s, 20);
152 // Here we probably should run
153 if (LyXVC::file_not_found_hook(s)) {
155 bformat(_("Do you want to retrieve the document"
156 " %1$s from version control?"), file);
157 int const ret = Alert::prompt(_("Retrieve from version control?"),
158 text, 0, 1, _("&Retrieve"), _("&Cancel"));
161 // How can we know _how_ to do the checkout?
162 // With the current VC support it has to be,
163 // a RCS file since CVS do not have special ,v files.
165 return loadLyXFile(b, s);
173 Buffer * newFile(string const & filename, string const & templatename,
177 Buffer * b = bufferlist.newBuffer(filename);
181 // use defaults.lyx as a default template if it exists.
182 if (templatename.empty())
183 tname = LibFileSearch("templates", "defaults.lyx");
185 tname = templatename;
187 if (!tname.empty()) {
188 if (!b->readFile(tname)) {
189 string const file = MakeDisplayPath(tname, 50);
190 string const text = bformat(_("The specified document template\n%1$s\ncould not be read."), file);
191 Alert::error(_("Could not read template"), text);
192 // no template, start with empty buffer
198 b->setFileName(filename);
201 b->setReadonly(false);
202 b->fully_loaded(true);
203 b->updateDocLang(b->params().language);
209 void bufferErrors(Buffer const & buf, TeXErrors const & terr)
211 TeXErrors::Errors::const_iterator cit = terr.begin();
212 TeXErrors::Errors::const_iterator end = terr.end();
214 for (; cit != end; ++cit) {
217 int errorrow = cit->error_in_line;
218 buf.texrow().getIdFromRow(errorrow, id_start, pos_start);
223 buf.texrow().getIdFromRow(errorrow, id_end, pos_end);
224 } while (id_start == id_end && pos_start == pos_end);
226 buf.error(ErrorItem(cit->error_desc, cit->error_text,
227 id_start, pos_start, pos_end));
232 void bufferErrors(Buffer const & buf, ErrorList const & el)
234 for_each(el.begin(), el.end(), bind(ref(buf.error), _1));
238 string const BufferFormat(Buffer const & buffer)
240 if (buffer.isLinuxDoc())
242 else if (buffer.isDocBook())
244 else if (buffer.isLiterate())
251 int countWords(DocIterator const & from, DocIterator const & to)
255 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
256 // Copied and adapted from isLetter() in ControlSpellChecker
258 && dit.pos() != dit.lastpos()
259 && dit.paragraph().isLetter(dit.pos())
260 && !isDeletedText(dit.paragraph(), dit.pos())) {
275 lyx::depth_type getDepth(DocIterator const & it)
277 lyx::depth_type depth = 0;
278 for (size_t i = 0 ; i < it.depth() ; ++i)
279 if (!it[i].inset().inMathed())
280 depth += it[i].paragraph().getDepth() + 1;
281 // remove 1 since the outer inset does not count
285 lyx::depth_type getItemDepth(ParIterator const & it)
287 Paragraph const & par = *it;
288 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
290 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
293 // this will hold the lowest depth encountered up to now.
294 lyx::depth_type min_depth = getDepth(it);
295 ParIterator prev_it = it;
298 --prev_it.top().pit();
300 // start of nested inset: go to outer par
302 if (prev_it.empty()) {
303 // start of document: nothing to do
308 // We search for the first paragraph with same label
309 // that is not more deeply nested.
310 Paragraph & prev_par = *prev_it;
311 lyx::depth_type const prev_depth = getDepth(prev_it);
312 if (labeltype == prev_par.layout()->labeltype) {
313 if (prev_depth < min_depth) {
314 return prev_par.itemdepth + 1;
316 else if (prev_depth == min_depth) {
317 return prev_par.itemdepth;
320 min_depth = std::min(min_depth, prev_depth);
321 // small optimization: if we are at depth 0, we won't
322 // find anything else
323 if (prev_depth == 0) {
330 bool needEnumCounterReset(ParIterator const & it)
332 Paragraph const & par = *it;
333 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
334 lyx::depth_type const cur_depth = par.getDepth();
335 ParIterator prev_it = it;
336 while (prev_it.pit()) {
337 --prev_it.top().pit();
338 Paragraph const & prev_par = *prev_it;
339 if (prev_par.getDepth() <= cur_depth)
340 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
342 // start of nested inset: reset
347 // set the counter of a paragraph. This includes the labels
348 void setCounter(Buffer const & buf, ParIterator & it)
350 Paragraph & par = *it;
351 BufferParams const & bufparams = buf.params();
352 LyXTextClass const & textclass = bufparams.getLyXTextClass();
353 LyXLayout_ptr const & layout = par.layout();
354 Counters & counters = textclass.counters();
357 par.params().appendix(par.params().startOfAppendix());
359 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
360 if (!par.params().appendix() &&
361 par.params().startOfAppendix()) {
362 par.params().appendix(true);
363 textclass.counters().reset();
367 // Compute the item depth of the paragraph
368 par.itemdepth = getItemDepth(it);
370 // erase what was there before
371 par.params().labelString(string());
373 if (layout->margintype == MARGIN_MANUAL) {
374 if (par.params().labelWidthString().empty())
375 par.setLabelWidthString(layout->labelstring());
377 par.setLabelWidthString(string());
380 // is it a layout that has an automatic label?
381 if (layout->labeltype == LABEL_COUNTER) {
382 if (layout->toclevel <= buf.params().secnumdepth
383 && (layout->latextype != LATEX_ENVIRONMENT
384 || isFirstInSequence(it.pit(), it.plist()))) {
385 counters.step(layout->counter);
386 string label = expandLabel(buf, layout,
387 par.params().appendix());
388 par.params().labelString(label);
390 } else if (layout->labeltype == LABEL_ITEMIZE) {
391 // At some point of time we should do something more
392 // clever here, like:
393 // par.params().labelString(
394 // bufparams.user_defined_bullet(par.itemdepth).getText());
395 // for now, use a simple hardcoded label
397 switch (par.itemdepth) {
412 par.params().labelString(itemlabel);
413 } else if (layout->labeltype == LABEL_ENUMERATE) {
415 // Yes I know this is a really, really! bad solution
417 string enumcounter = "enum";
419 switch (par.itemdepth) {
431 // not a valid enumdepth...
435 // Maybe we have to reset the enumeration counter.
436 if (needEnumCounterReset(it))
437 counters.reset(enumcounter);
439 counters.step(enumcounter);
443 switch (par.itemdepth) {
445 format = N_("\\arabic{enumi}.");
448 format = N_("(\\alph{enumii})");
451 format = N_("\\roman{enumiii}.");
454 format = N_("\\Alph{enumiv}.");
457 // not a valid enumdepth...
461 par.params().labelString(counters.counterLabel(buf.B_(format)));
462 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
463 counters.step("bibitem");
464 int number = counters.value("bibitem");
466 par.bibitem()->setCounter(number);
467 par.params().labelString(buf.B_(layout->labelstring()));
468 // In biblio should't be following counters but...
469 } else if (layout->labeltype == LABEL_SENSITIVE) {
470 // Search for the first float or wrap inset in the iterator
472 size_t i = it.depth();
475 InsetBase * const in = &it[i].inset();
476 if (in->lyxCode() == InsetBase::FLOAT_CODE
477 || in->lyxCode() == InsetBase::WRAP_CODE)
478 type = in->getInsetName();
484 Floating const & fl = textclass.floats().getType(type);
486 counters.step(fl.type());
488 // Doesn't work... yet.
489 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
491 // par->SetLayout(0);
492 s = buf.B_(layout->labelstring());
495 par.params().labelString(s);
497 par.params().labelString(buf.B_(layout->labelstring()));
503 void updateCounters(Buffer const & buf)
506 buf.params().getLyXTextClass().counters().reset();
508 for (ParIterator it = par_iterator_begin(buf.inset()); it; ++it) {
509 // reduce depth if necessary
511 Paragraph const & prevpar = it.plist()[it.pit() - 1];
512 it->params().depth(min(it->params().depth(),
513 prevpar.getMaxDepthAfter()));
515 it->params().depth(0);
517 // set the counter for this paragraph
523 string expandLabel(Buffer const & buf,
524 LyXLayout_ptr const & layout, bool appendix)
526 LyXTextClass const & tclass = buf.params().getLyXTextClass();
528 string fmt = buf.B_(appendix ? layout->labelstring_appendix()
529 : layout->labelstring());
531 // handle 'inherited level parts' in 'fmt',
532 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
533 size_t const i = fmt.find('@', 0);
534 if (i != string::npos) {
535 size_t const j = fmt.find('@', i + 1);
536 if (j != string::npos) {
537 string parent(fmt, i + 1, j - i - 1);
538 string label = expandLabel(buf, tclass[parent], appendix);
539 fmt = string(fmt, 0, i) + label + string(fmt, j + 1, string::npos);
543 return tclass.counters().counterLabel(fmt);