]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.C
improve selection of range when using the errorlist dialog
[lyx.git] / src / buffer_funcs.C
1 /**
2  * \file buffer_funcs.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16
17 #include "buffer.h"
18 #include "bufferlist.h"
19 #include "bufferparams.h"
20 #include "dociterator.h"
21 #include "counters.h"
22 #include "errorlist.h"
23 #include "Floating.h"
24 #include "FloatList.h"
25 #include "gettext.h"
26 #include "LaTeX.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"
33 #include "lyxvc.h"
34 #include "texrow.h"
35 #include "vc-backend.h"
36
37 #include "frontends/Alert.h"
38
39 #include "insets/insetbibitem.h"
40
41 #include "support/filetools.h"
42 #include "support/fs_extras.h"
43 #include "support/lyxlib.h"
44
45 #include <boost/bind.hpp>
46 #include <boost/filesystem/operations.hpp>
47
48 using lyx::pit_type;
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;
55
56 using std::min;
57 using std::string;
58
59 namespace fs = boost::filesystem;
60
61 extern BufferList bufferlist;
62
63 namespace {
64
65 bool readFile(Buffer * const b, string const & s)
66 {
67         BOOST_ASSERT(b);
68
69         // File information about normal file
70         if (!fs::exists(s)) {
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);
75                 return false;
76         }
77
78         // Check if emergency save file exists and is newer.
79         string const e = OnlyPath(s) + OnlyFilename(s) + ".emergency";
80
81         if (fs::exists(e) && fs::exists(s)
82             && fs::last_write_time(e) > fs::last_write_time(s))
83         {
84                 string const file = MakeDisplayPath(s, 20);
85                 string const text =
86                         bformat(_("An emergency save of the document "
87                                   "%1$s exists.\n\n"
88                                   "Recover emergency save?"), file);
89                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
90                                       _("&Recover"),  _("&Load Original"),
91                                       _("&Cancel")))
92                 {
93                 case 0:
94                         // the file is not saved if we load the emergency file.
95                         b->markDirty();
96                         return b->readFile(e);
97                 case 1:
98                         break;
99                 default:
100                         return false;
101                 }
102         }
103
104         // Now check if autosave file is newer.
105         string const a = OnlyPath(s) + '#' + OnlyFilename(s) + '#';
106
107         if (fs::exists(a) && fs::exists(s)
108             && fs::last_write_time(a) > fs::last_write_time(s))
109         {
110                 string const file = MakeDisplayPath(s, 20);
111                 string const text =
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"),
117                                       _("&Cancel") ))
118                 {
119                 case 0:
120                         // the file is not saved if we load the autosave file.
121                         b->markDirty();
122                         return b->readFile(a);
123                 case 1:
124                         // Here we delete the autosave
125                         unlink(a);
126                         break;
127                 default:
128                         return false;
129                 }
130         }
131         return b->readFile(s);
132 }
133
134
135 } // namespace anon
136
137
138
139 bool loadLyXFile(Buffer * b, string const & s)
140 {
141         BOOST_ASSERT(b);
142
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);
148                         return true;
149                 }
150         } else {
151                 string const file = MakeDisplayPath(s, 20);
152                 // Here we probably should run
153                 if (LyXVC::file_not_found_hook(s)) {
154                         string const text =
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"));
159
160                         if (ret == 0) {
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.
164                                 RCS::retrieve(s);
165                                 return loadLyXFile(b, s);
166                         }
167                 }
168         }
169         return false;
170 }
171
172
173 Buffer * newFile(string const & filename, string const & templatename,
174                  bool const isNamed)
175 {
176         // get a free buffer
177         Buffer * b = bufferlist.newBuffer(filename);
178         BOOST_ASSERT(b);
179
180         string tname;
181         // use defaults.lyx as a default template if it exists.
182         if (templatename.empty())
183                 tname = LibFileSearch("templates", "defaults.lyx");
184         else
185                 tname = templatename;
186
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
193                 }
194         }
195
196         if (!isNamed) {
197                 b->setUnnamed();
198                 b->setFileName(filename);
199         }
200
201         b->setReadonly(false);
202         b->fully_loaded(true);
203         b->updateDocLang(b->params().language);
204
205         return b;
206 }
207
208
209 void bufferErrors(Buffer const & buf, TeXErrors const & terr)
210 {
211         TeXErrors::Errors::const_iterator cit = terr.begin();
212         TeXErrors::Errors::const_iterator end = terr.end();
213
214         for (; cit != end; ++cit) {
215                 int id_start = -1;
216                 int pos_start = -1;
217                 int errorrow = cit->error_in_line;
218                 buf.texrow().getIdFromRow(errorrow, id_start, pos_start);
219                 int id_end = -1;
220                 int pos_end = -1;
221                 do {
222                         ++errorrow;
223                         buf.texrow().getIdFromRow(errorrow, id_end, pos_end);
224                 } while (id_start == id_end && pos_start == pos_end);
225
226                 buf.error(ErrorItem(cit->error_desc, cit->error_text,
227                                     id_start, pos_start, pos_end));
228         }
229 }
230
231
232 void bufferErrors(Buffer const & buf, ErrorList const & el)
233 {
234         for_each(el.begin(), el.end(), bind(ref(buf.error), _1));
235 }
236
237
238 string const BufferFormat(Buffer const & buffer)
239 {
240         if (buffer.isLinuxDoc())
241                 return "linuxdoc";
242         else if (buffer.isDocBook())
243                 return "docbook";
244         else if (buffer.isLiterate())
245                 return "literate";
246         else
247                 return "latex";
248 }
249
250
251 int countWords(DocIterator const & from, DocIterator const & to)
252 {
253         int count = 0;
254         bool inword = false;
255         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
256                 // Copied and adapted from isLetter() in ControlSpellChecker
257                 if (dit.inTexted()
258                     && dit.pos() != dit.lastpos()
259                     && dit.paragraph().isLetter(dit.pos())
260                     && !isDeletedText(dit.paragraph(), dit.pos())) {
261                         if (!inword) {
262                                 ++count;
263                                 inword = true;
264                         }
265                 } else if (inword)
266                         inword = false;
267         }
268
269         return count;
270 }
271
272
273 namespace {
274
275 void incrementItemDepth(ParagraphList & pars, pit_type pit, pit_type first_pit)
276 {
277         int const cur_labeltype = pars[pit].layout()->labeltype;
278
279         if (cur_labeltype != LABEL_ENUMERATE && cur_labeltype != LABEL_ITEMIZE)
280                 return;
281
282         int const cur_depth = pars[pit].getDepth();
283
284         pit_type prev_pit = pit - 1;
285         while (true) {
286                 int const prev_depth = pars[prev_pit].getDepth();
287                 int const prev_labeltype = pars[prev_pit].layout()->labeltype;
288                 if (prev_depth == 0 && cur_depth > 0) {
289                         if (prev_labeltype == cur_labeltype) {
290                                 pars[pit].itemdepth = pars[prev_pit].itemdepth + 1;
291                         }
292                         break;
293                 } else if (prev_depth < cur_depth) {
294                         if (prev_labeltype == cur_labeltype) {
295                                 pars[pit].itemdepth = pars[prev_pit].itemdepth + 1;
296                                 break;
297                         }
298                 } else if (prev_depth == cur_depth) {
299                         if (prev_labeltype == cur_labeltype) {
300                                 pars[pit].itemdepth = pars[prev_pit].itemdepth;
301                                 break;
302                         }
303                 }
304                 if (prev_pit == first_pit)
305                         break;
306
307                 --prev_pit;
308         }
309 }
310
311
312 void resetEnumCounterIfNeeded(ParagraphList & pars, pit_type pit,
313         pit_type firstpit, Counters & counters)
314 {
315         if (pit == firstpit)
316                 return;
317
318         int const cur_depth = pars[pit].getDepth();
319         pit_type prev_pit = pit - 1;
320         while (true) {
321                 int const prev_depth = pars[prev_pit].getDepth();
322                 int const prev_labeltype = pars[prev_pit].layout()->labeltype;
323                 if (prev_depth <= cur_depth) {
324                         if (prev_labeltype != LABEL_ENUMERATE) {
325                                 switch (pars[pit].itemdepth) {
326                                 case 0:
327                                         counters.reset("enumi");
328                                 case 1:
329                                         counters.reset("enumii");
330                                 case 2:
331                                         counters.reset("enumiii");
332                                 case 3:
333                                         counters.reset("enumiv");
334                                 }
335                         }
336                         break;
337                 }
338
339                 if (prev_pit == firstpit)
340                         break;
341
342                 --prev_pit;
343         }
344 }
345
346
347 // set the counter of a paragraph. This includes the labels
348 void setCounter(Buffer const & buf, ParIterator & it)
349 {
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();
355
356         // Always reset
357         par.itemdepth = 0;
358
359         if (it.pit() == 0) {
360                 par.params().appendix(par.params().startOfAppendix());
361         } else {
362                 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
363                 if (!par.params().appendix() &&
364                     par.params().startOfAppendix()) {
365                         par.params().appendix(true);
366                         textclass.counters().reset();
367                 }
368
369                 // Maybe we have to increment the item depth.
370                 incrementItemDepth(it.plist(), it.pit(), 0);
371         }
372
373         // erase what was there before
374         par.params().labelString(string());
375
376         if (layout->margintype == MARGIN_MANUAL) {
377                 if (par.params().labelWidthString().empty())
378                         par.setLabelWidthString(layout->labelstring());
379         } else {
380                 par.setLabelWidthString(string());
381         }
382
383         // is it a layout that has an automatic label?
384         if (layout->labeltype == LABEL_COUNTER) {
385                 if (layout->toclevel <= buf.params().secnumdepth
386                     && (layout->latextype != LATEX_ENVIRONMENT
387                         || isFirstInSequence(it.pit(), it.plist()))) {
388                         counters.step(layout->counter);
389                         string label = expandLabel(buf, layout,
390                                                    par.params().appendix());
391                         par.params().labelString(label);
392                 }
393         } else if (layout->labeltype == LABEL_ITEMIZE) {
394                 // At some point of time we should do something more
395                 // clever here, like:
396                 //   par.params().labelString(
397                 //    bufparams.user_defined_bullet(par.itemdepth).getText());
398                 // for now, use a simple hardcoded label
399                 string itemlabel;
400                 switch (par.itemdepth) {
401                 case 0:
402                         itemlabel = "*";
403                         break;
404                 case 1:
405                         itemlabel = "-";
406                         break;
407                 case 2:
408                         itemlabel = "@";
409                         break;
410                 case 3:
411                         itemlabel = "·";
412                         break;
413                 }
414
415                 par.params().labelString(itemlabel);
416         } else if (layout->labeltype == LABEL_ENUMERATE) {
417                 // Maybe we have to reset the enumeration counter.
418                 resetEnumCounterIfNeeded(it.plist(), it.pit(), 0, counters);
419
420                 // FIXME
421                 // Yes I know this is a really, really! bad solution
422                 // (Lgb)
423                 string enumcounter = "enum";
424
425                 switch (par.itemdepth) {
426                 case 2:
427                         enumcounter += 'i';
428                 case 1:
429                         enumcounter += 'i';
430                 case 0:
431                         enumcounter += 'i';
432                         break;
433                 case 3:
434                         enumcounter += "iv";
435                         break;
436                 default:
437                         // not a valid enumdepth...
438                         break;
439                 }
440
441                 counters.step(enumcounter);
442
443                 par.params().labelString(counters.enumLabel(enumcounter));
444         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
445                 counters.step("bibitem");
446                 int number = counters.value("bibitem");
447                 if (par.bibitem()) 
448                         par.bibitem()->setCounter(number);
449                 par.params().labelString(buf.B_(layout->labelstring()));
450                 // In biblio should't be following counters but...
451         } else if (layout->labeltype == LABEL_SENSITIVE) {
452                 // Search for the first float or wrap inset in the iterator
453                 string type;
454                 size_t i = it.depth();
455                 while (i > 0) {
456                         --i;
457                         InsetBase * const in = &it[i].inset();
458                         if (in->lyxCode() == InsetBase::FLOAT_CODE
459                             || in->lyxCode() == InsetBase::WRAP_CODE)
460                                 type = in->getInsetName();
461                                 break;
462                 }
463
464                 string s;
465                 if (!type.empty()) {
466                         Floating const & fl = textclass.floats().getType(type);
467
468                         counters.step(fl.type());
469
470                         // Doesn't work... yet.
471                         s = bformat(_("%1$s #:"), buf.B_(fl.name()));
472                 } else {
473                         // par->SetLayout(0);
474                         s = buf.B_(layout->labelstring());
475                 }
476
477                 par.params().labelString(s);
478         } else
479                 par.params().labelString(buf.B_(layout->labelstring()));
480 }
481
482 } // anon namespace
483
484
485 void updateCounters(Buffer const & buf)
486 {
487         // start over
488         buf.params().getLyXTextClass().counters().reset();
489
490         for (ParIterator it = par_iterator_begin(buf.inset()); it; ++it) {
491                 // reduce depth if necessary
492                 if (it.pit()) {
493                         Paragraph const & prevpar = it.plist()[it.pit() - 1];
494                         it->params().depth(min(it->params().depth(),
495                                                prevpar.getMaxDepthAfter()));
496                 } else
497                         it->params().depth(0);
498
499                 // set the counter for this paragraph
500                 setCounter(buf, it);
501         }
502 }
503
504
505 string expandLabel(Buffer const & buf,
506         LyXLayout_ptr const & layout, bool appendix)
507 {
508         LyXTextClass const & tclass = buf.params().getLyXTextClass();
509
510         string fmt = buf.B_(appendix ? layout->labelstring_appendix() 
511                             : layout->labelstring());
512
513         // handle 'inherited level parts' in 'fmt',
514         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
515         size_t const i = fmt.find('@', 0);
516         if (i != string::npos) {
517                 size_t const j = fmt.find('@', i + 1);
518                 if (j != string::npos) {
519                         string parent(fmt, i + 1, j - i - 1);
520                         string label = expandLabel(buf, tclass[parent], appendix);
521                         fmt = string(fmt, 0, i) + label + string(fmt, j + 1, string::npos);
522                 }
523         }
524
525         return tclass.counters().counterLabel(fmt);
526 }
527
528