]> git.lyx.org Git - features.git/blob - src/buffer_funcs.cpp
more use of support::FileName.
[features.git] / src / buffer_funcs.cpp
1 /**
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.
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 #include "Buffer.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "debug.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 "InsetList.h"
27 #include "InsetIterator.h"
28 #include "Language.h"
29 #include "LaTeX.h"
30 #include "Layout.h"
31 #include "LayoutPtr.h"
32 #include "LyX.h"
33 #include "TextClass.h"
34 #include "TextClassList.h"
35 #include "Paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphList.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "TexRow.h"
41 #include "Text.h"
42 #include "TocBackend.h"
43
44 #include "frontends/alert.h"
45
46 #include "insets/InsetBibitem.h"
47 #include "insets/InsetInclude.h"
48
49 #include "support/filetools.h"
50 #include "support/lyxlib.h"
51
52 using std::min;
53 using std::string;
54
55
56 namespace lyx {
57
58 using namespace std;
59
60 using support::bformat;
61 using support::FileName;
62 using support::libFileSearch;
63 using support::makeAbsPath;
64 using support::makeDisplayPath;
65 using support::onlyFilename;
66 using support::onlyPath;
67 using support::unlink;
68
69 namespace Alert = frontend::Alert;
70
71
72 Buffer * checkAndLoadLyXFile(FileName const & filename)
73 {
74         // File already open?
75         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
76         if (checkBuffer) {
77                 if (checkBuffer->isClean())
78                         return checkBuffer;
79                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
80                 docstring text = bformat(_(
81                                 "The document %1$s is already loaded and has unsaved changes.\n"
82                                 "Do you want to abandon your changes and reload the version on disk?"), file);
83                 if (Alert::prompt(_("Reload saved document?"),
84                                 text, 0, 1,  _("&Reload"), _("&Keep Changes")))
85                         return checkBuffer;
86
87                 // FIXME: should be LFUN_REVERT
88                 if (theBufferList().close(checkBuffer, false))
89                         // Load it again.
90                         return checkAndLoadLyXFile(filename);
91                 // The file could not be closed.
92                 return 0;
93         }
94
95         if (filename.isReadable()) {
96                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
97                 if (!b->loadLyXFile(filename)) {
98                         theBufferList().release(b);
99                         return 0;
100                 }
101                 return b;
102         }
103
104         docstring text = bformat(_("The document %1$s does not yet "
105                 "exist.\n\nDo you want to create a new document?"),
106                 from_utf8(filename.absFilename()));
107         if (!Alert::prompt(_("Create new document?"),
108                         text, 0, 1, _("&Create"), _("Cancel")))
109                 return newFile(filename.absFilename(), string(), true);
110
111         return 0;
112 }
113
114
115 // FIXME newFile() should probably be a member method of Application...
116 Buffer * newFile(string const & filename, string const & templatename,
117                  bool const isNamed)
118 {
119         // get a free buffer
120         Buffer * b = theBufferList().newBuffer(filename);
121         BOOST_ASSERT(b);
122
123         FileName tname;
124         // use defaults.lyx as a default template if it exists.
125         if (templatename.empty())
126                 tname = libFileSearch("templates", "defaults.lyx");
127         else
128                 tname = makeAbsPath(templatename);
129
130         if (!tname.empty()) {
131                 if (!b->readFile(tname)) {
132                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
133                         docstring const text  = bformat(
134                                 _("The specified document template\n%1$s\ncould not be read."),
135                                 file);
136                         Alert::error(_("Could not read template"), text);
137                         theBufferList().release(b);
138                         return 0;
139                 }
140         }
141
142         if (!isNamed) {
143                 b->setUnnamed();
144                 b->setFileName(filename);
145         }
146
147         b->setReadonly(false);
148         b->setFullyLoaded(true);
149
150         return b;
151 }
152
153
154 int countWords(DocIterator const & from, DocIterator const & to)
155 {
156         int count = 0;
157         bool inword = false;
158         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
159                 // Copied and adapted from isLetter() in ControlSpellChecker
160                 if (dit.inTexted()
161                     && dit.pos() != dit.lastpos()
162                     && dit.paragraph().isLetter(dit.pos())
163                     && !dit.paragraph().isDeleted(dit.pos())) {
164                         if (!inword) {
165                                 ++count;
166                                 inword = true;
167                         }
168                 } else if (inword)
169                         inword = false;
170         }
171
172         return count;
173 }
174
175
176 namespace {
177
178 depth_type getDepth(DocIterator const & it)
179 {
180         depth_type depth = 0;
181         for (size_t i = 0 ; i < it.depth() ; ++i)
182                 if (!it[i].inset().inMathed())
183                         depth += it[i].paragraph().getDepth() + 1;
184         // remove 1 since the outer inset does not count
185         return depth - 1;
186 }
187
188 depth_type getItemDepth(ParIterator const & it)
189 {
190         Paragraph const & par = *it;
191         LabelType const labeltype = par.layout()->labeltype;
192
193         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
194                 return 0;
195
196         // this will hold the lowest depth encountered up to now.
197         depth_type min_depth = getDepth(it);
198         ParIterator prev_it = it;
199         while (true) {
200                 if (prev_it.pit())
201                         --prev_it.top().pit();
202                 else {
203                         // start of nested inset: go to outer par
204                         prev_it.pop_back();
205                         if (prev_it.empty()) {
206                                 // start of document: nothing to do
207                                 return 0;
208                         }
209                 }
210
211                 // We search for the first paragraph with same label
212                 // that is not more deeply nested.
213                 Paragraph & prev_par = *prev_it;
214                 depth_type const prev_depth = getDepth(prev_it);
215                 if (labeltype == prev_par.layout()->labeltype) {
216                         if (prev_depth < min_depth)
217                                 return prev_par.itemdepth + 1;
218                         if (prev_depth == min_depth)
219                                 return prev_par.itemdepth;
220                 }
221                 min_depth = std::min(min_depth, prev_depth);
222                 // small optimization: if we are at depth 0, we won't
223                 // find anything else
224                 if (prev_depth == 0)
225                         return 0;
226         }
227 }
228
229
230 bool needEnumCounterReset(ParIterator const & it)
231 {
232         Paragraph const & par = *it;
233         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
234         depth_type const cur_depth = par.getDepth();
235         ParIterator prev_it = it;
236         while (prev_it.pit()) {
237                 --prev_it.top().pit();
238                 Paragraph const & prev_par = *prev_it;
239                 if (prev_par.getDepth() <= cur_depth)
240                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
241         }
242         // start of nested inset: reset
243         return true;
244 }
245
246
247 // set the label of a paragraph. This includes the counters.
248 void setLabel(Buffer const & buf, ParIterator & it)
249 {
250         TextClass const & textclass = buf.params().getTextClass();
251         Paragraph & par = it.paragraph();
252         LayoutPtr const & layout = par.layout();
253         Counters & counters = textclass.counters();
254
255         if (par.params().startOfAppendix()) {
256                 // FIXME: only the counter corresponding to toplevel
257                 // sectionning should be reset
258                 counters.reset();
259                 counters.appendix(true);
260         }
261         par.params().appendix(counters.appendix());
262
263         // Compute the item depth of the paragraph
264         par.itemdepth = getItemDepth(it);
265
266         if (layout->margintype == MARGIN_MANUAL) {
267                 if (par.params().labelWidthString().empty())
268                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
269         } else {
270                 par.params().labelWidthString(docstring());
271         }
272
273         switch(layout->labeltype) {
274         case LABEL_COUNTER:
275                 if (layout->toclevel <= buf.params().secnumdepth
276                     && (layout->latextype != LATEX_ENVIRONMENT
277                         || isFirstInSequence(it.pit(), it.plist()))) {
278                         counters.step(layout->counter);
279                         par.params().labelString(
280                                 par.expandLabel(layout, buf.params()));
281                 } else
282                         par.params().labelString(docstring());
283                 break;
284
285         case LABEL_ITEMIZE: {
286                 // At some point of time we should do something more
287                 // clever here, like:
288                 //   par.params().labelString(
289                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
290                 // for now, use a simple hardcoded label
291                 docstring itemlabel;
292                 switch (par.itemdepth) {
293                 case 0:
294                         itemlabel = char_type(0x2022);
295                         break;
296                 case 1:
297                         itemlabel = char_type(0x2013);
298                         break;
299                 case 2:
300                         itemlabel = char_type(0x2217);
301                         break;
302                 case 3:
303                         itemlabel = char_type(0x2219); // or 0x00b7
304                         break;
305                 }
306                 par.params().labelString(itemlabel);
307                 break;
308         }
309
310         case LABEL_ENUMERATE: {
311                 // FIXME: Yes I know this is a really, really! bad solution
312                 // (Lgb)
313                 docstring enumcounter = from_ascii("enum");
314
315                 switch (par.itemdepth) {
316                 case 2:
317                         enumcounter += 'i';
318                 case 1:
319                         enumcounter += 'i';
320                 case 0:
321                         enumcounter += 'i';
322                         break;
323                 case 3:
324                         enumcounter += "iv";
325                         break;
326                 default:
327                         // not a valid enumdepth...
328                         break;
329                 }
330
331                 // Maybe we have to reset the enumeration counter.
332                 if (needEnumCounterReset(it))
333                         counters.reset(enumcounter);
334
335                 counters.step(enumcounter);
336
337                 string format;
338
339                 switch (par.itemdepth) {
340                 case 0:
341                         format = N_("\\arabic{enumi}.");
342                         break;
343                 case 1:
344                         format = N_("(\\alph{enumii})");
345                         break;
346                 case 2:
347                         format = N_("\\roman{enumiii}.");
348                         break;
349                 case 3:
350                         format = N_("\\Alph{enumiv}.");
351                         break;
352                 default:
353                         // not a valid enumdepth...
354                         break;
355                 }
356
357                 par.params().labelString(counters.counterLabel(
358                         par.translateIfPossible(from_ascii(format), buf.params())));
359
360                 break;
361         }
362
363         case LABEL_SENSITIVE: {
364                 string const & type = counters.current_float();
365                 docstring full_label;
366                 if (type.empty())
367                         full_label = buf.B_("Senseless!!! ");
368                 else {
369                         docstring name = buf.B_(textclass.floats().getType(type).name());
370                         if (counters.hasCounter(from_utf8(type))) {
371                                 counters.step(from_utf8(type));
372                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
373                                                      name, 
374                                                      counters.theCounter(from_utf8(type)));
375                         } else
376                                 full_label = bformat(from_ascii("%1$s #:"), name);      
377                 }
378                 par.params().labelString(full_label);   
379                 break;
380         }
381
382         case LABEL_NO_LABEL:
383                 par.params().labelString(docstring());
384                 break;
385
386         case LABEL_MANUAL:
387         case LABEL_TOP_ENVIRONMENT:
388         case LABEL_CENTERED_TOP_ENVIRONMENT:
389         case LABEL_STATIC:      
390         case LABEL_BIBLIO:
391                 par.params().labelString(
392                         par.translateIfPossible(layout->labelstring(), 
393                                                 buf.params()));
394                 break;
395         }
396 }
397
398 } // anon namespace
399
400 void updateLabels(Buffer const & buf, ParIterator & parit)
401 {
402         BOOST_ASSERT(parit.pit() == 0);
403
404         depth_type maxdepth = 0;
405         pit_type const lastpit = parit.lastpit();
406         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
407                 // reduce depth if necessary
408                 parit->params().depth(min(parit->params().depth(), maxdepth));
409                 maxdepth = parit->getMaxDepthAfter();
410
411                 // set the counter for this paragraph
412                 setLabel(buf, parit);
413
414                 // Now the insets
415                 InsetList::const_iterator iit = parit->insetList().begin();
416                 InsetList::const_iterator end = parit->insetList().end();
417                 for (; iit != end; ++iit) {
418                         parit.pos() = iit->pos;
419                         iit->inset->updateLabels(buf, parit);
420                 }
421         }
422         
423 }
424
425
426 // FIXME: buf should should be const because updateLabels() modifies
427 // the contents of the paragraphs.
428 void updateLabels(Buffer const & buf, bool childonly)
429 {
430         Buffer const * const master = buf.masterBuffer();
431         // Use the master text class also for child documents
432         TextClass const & textclass = master->params().getTextClass();
433
434         if (!childonly) {
435                 // If this is a child document start with the master
436                 if (master != &buf) {
437                         updateLabels(*master);
438                         return;
439                 }
440
441                 // start over the counters
442                 textclass.counters().reset();
443         }
444
445         Buffer & cbuf = const_cast<Buffer &>(buf);
446
447         if (buf.text().empty()) {
448                 // FIXME: we don't call continue with updateLabels()
449                 // here because it crashes on newly created documents.
450                 // But the TocBackend needs to be initialised
451                 // nonetheless so we update the tocBackend manually.
452                 cbuf.tocBackend().update();
453                 return;
454         }
455
456         // do the real work
457         ParIterator parit = par_iterator_begin(buf.inset());
458         updateLabels(buf, parit);
459
460         cbuf.tocBackend().update();
461         if (!childonly)
462                 cbuf.structureChanged();
463 }
464
465
466 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
467 {
468         if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
469                 Buffer * master = buffer.masterBuffer();
470                 master->tocBackend().updateItem(par_it);
471                 master->structureChanged();
472         }
473 }
474
475
476 } // namespace lyx