]> git.lyx.org Git - features.git/blob - src/buffer.C
factorise linuxdoc and docbook output code
[features.git] / src / buffer.C
1 /**
2  * \file buffer.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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "Bullet.h"
20 #include "Chktex.h"
21 #include "debug.h"
22 #include "errorlist.h"
23 #include "exporter.h"
24 #include "format.h"
25 #include "funcrequest.h"
26 #include "gettext.h"
27 #include "iterators.h"
28 #include "language.h"
29 #include "LaTeX.h"
30 #include "LaTeXFeatures.h"
31 #include "LyXAction.h"
32 #include "lyxlex.h"
33 #include "lyxrc.h"
34 #include "lyxvc.h"
35 #include "messages.h"
36 #include "paragraph.h"
37 #include "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
39 #include "sgml.h"
40 #include "texrow.h"
41 #include "undo.h"
42 #include "version.h"
43
44 #include "insets/insetbibitem.h"
45 #include "insets/insetbibtex.h"
46 #include "insets/insetinclude.h"
47 #include "insets/insettext.h"
48
49 #include "frontends/Alert.h"
50
51 #include "graphics/Previews.h"
52
53 #include "support/FileInfo.h"
54 #include "support/filetools.h"
55 #include "support/gzstream.h"
56 #include "support/lyxlib.h"
57 #include "support/os.h"
58 #include "support/path.h"
59 #include "support/textutils.h"
60 #include "support/tostr.h"
61
62 #include <boost/bind.hpp>
63
64 #include "support/std_sstream.h"
65
66 #include <iomanip>
67 #include <stack>
68
69 #include <utime.h>
70
71 #ifdef HAVE_LOCALE
72 #endif
73
74 using lyx::pos_type;
75
76 using lyx::support::AddName;
77 using lyx::support::ascii_lowercase;
78 using lyx::support::atoi;
79 using lyx::support::bformat;
80 using lyx::support::ChangeExtension;
81 using lyx::support::cmd_ret;
82 using lyx::support::compare_ascii_no_case;
83 using lyx::support::compare_no_case;
84 using lyx::support::contains;
85 using lyx::support::CreateBufferTmpDir;
86 using lyx::support::destroyDir;
87 using lyx::support::FileInfo;
88 using lyx::support::FileInfo;
89 using lyx::support::getExtFromContents;
90 using lyx::support::IsDirWriteable;
91 using lyx::support::IsFileWriteable;
92 using lyx::support::LibFileSearch;
93 using lyx::support::ltrim;
94 using lyx::support::MakeAbsPath;
95 using lyx::support::MakeDisplayPath;
96 using lyx::support::MakeLatexName;
97 using lyx::support::OnlyFilename;
98 using lyx::support::OnlyPath;
99 using lyx::support::Path;
100 using lyx::support::QuoteName;
101 using lyx::support::removeAutosaveFile;
102 using lyx::support::rename;
103 using lyx::support::RunCommand;
104 using lyx::support::split;
105 using lyx::support::strToInt;
106 using lyx::support::subst;
107 using lyx::support::tempName;
108 using lyx::support::trim;
109
110 namespace os = lyx::support::os;
111
112 using std::endl;
113 using std::for_each;
114 using std::make_pair;
115
116 using std::ifstream;
117 using std::ios;
118 using std::ostream;
119 using std::ostringstream;
120 using std::ofstream;
121 using std::pair;
122 using std::stack;
123 using std::vector;
124 using std::string;
125
126
127 // all these externs should eventually be removed.
128 extern BufferList bufferlist;
129
130 namespace {
131
132 const int LYX_FORMAT = 225;
133
134 bool openFileWrite(ofstream & ofs, string const & fname)
135 {
136         ofs.open(fname.c_str());
137         if (!ofs) {
138                 string const file = MakeDisplayPath(fname, 50);
139                 string text = bformat(_("Could not open the specified "
140                                         "document\n%1$s."), file);
141                 Alert::error(_("Could not open file"), text);
142                 return false;
143         }
144         return true;
145 }
146
147 } // namespace anon
148
149
150 typedef std::map<string, bool> DepClean;
151
152 struct Buffer::Impl
153 {
154         Impl(Buffer & parent, string const & file, bool readonly);
155
156         limited_stack<Undo> undostack;
157         limited_stack<Undo> redostack;
158         BufferParams params;
159         ParagraphList paragraphs;
160         LyXVC lyxvc;
161         string temppath;
162         bool nicefile;
163         TexRow texrow;
164
165         /// need to regenerate .tex ?
166         DepClean dep_clean;
167
168         /// is save needed
169         mutable bool lyx_clean;
170
171         /// is autosave needed
172         mutable bool bak_clean;
173
174         /// is this a unnamed file (New...)
175         bool unnamed;
176
177         /// buffer is r/o
178         bool read_only;
179
180         /// name of the file the buffer is associated with.
181         string filename;
182
183         /// The path to the document file.
184         string filepath;
185
186         boost::scoped_ptr<Messages> messages;
187
188         /** set to true only when the file is fully loaded.
189          *  Used to prevent the premature generation of previews
190          *  and by the citation inset.
191          */
192         bool file_fully_loaded;
193 };
194
195
196 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
197         : nicefile(true),
198           lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
199           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false)
200 {
201         lyxvc.buffer(&parent);
202         if (readonly_ || lyxrc.use_tempdir)
203                 temppath = CreateBufferTmpDir();
204 }
205
206
207 Buffer::Buffer(string const & file, bool ronly)
208         : pimpl_(new Impl(*this, file, ronly))
209 {
210         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
211 }
212
213
214 Buffer::~Buffer()
215 {
216         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
217         // here the buffer should take care that it is
218         // saved properly, before it goes into the void.
219
220         closing();
221
222         if (!temppath().empty() && destroyDir(temppath()) != 0) {
223                 Alert::warning(_("Could not remove temporary directory"),
224                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
225         }
226
227         paragraphs().clear();
228
229         // Remove any previewed LaTeX snippets associated with this buffer.
230         lyx::graphics::Previews::get().removeLoader(*this);
231 }
232
233
234 limited_stack<Undo> & Buffer::undostack()
235 {
236         return pimpl_->undostack;
237 }
238
239
240 limited_stack<Undo> const & Buffer::undostack() const
241 {
242         return pimpl_->undostack;
243 }
244
245
246 limited_stack<Undo> & Buffer::redostack()
247 {
248         return pimpl_->redostack;
249 }
250
251
252 limited_stack<Undo> const & Buffer::redostack() const
253 {
254         return pimpl_->redostack;
255 }
256
257
258 BufferParams & Buffer::params()
259 {
260         return pimpl_->params;
261 }
262
263
264 BufferParams const & Buffer::params() const
265 {
266         return pimpl_->params;
267 }
268
269
270 ParagraphList & Buffer::paragraphs()
271 {
272         return pimpl_->paragraphs;
273 }
274
275
276 ParagraphList const & Buffer::paragraphs() const
277 {
278         return pimpl_->paragraphs;
279 }
280
281
282 LyXVC & Buffer::lyxvc()
283 {
284         return pimpl_->lyxvc;
285 }
286
287
288 LyXVC const & Buffer::lyxvc() const
289 {
290         return pimpl_->lyxvc;
291 }
292
293
294 string const & Buffer::temppath() const
295 {
296         return pimpl_->temppath;
297 }
298
299
300 bool & Buffer::niceFile()
301 {
302         return pimpl_->nicefile;
303 }
304
305
306 bool Buffer::niceFile() const
307 {
308         return pimpl_->nicefile;
309 }
310
311
312 TexRow & Buffer::texrow()
313 {
314         return pimpl_->texrow;
315 }
316
317
318 TexRow const & Buffer::texrow() const
319 {
320         return pimpl_->texrow;
321 }
322
323
324 string const Buffer::getLatexName(bool no_path) const
325 {
326         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
327         return no_path ? OnlyFilename(name) : name;
328 }
329
330
331 pair<Buffer::LogType, string> const Buffer::getLogName() const
332 {
333         string const filename = getLatexName(false);
334
335         if (filename.empty())
336                 return make_pair(Buffer::latexlog, string());
337
338         string path = OnlyPath(filename);
339
340         if (lyxrc.use_tempdir || !IsDirWriteable(path))
341                 path = temppath();
342
343         string const fname = AddName(path,
344                                      OnlyFilename(ChangeExtension(filename,
345                                                                   ".log")));
346         string const bname =
347                 AddName(path, OnlyFilename(
348                         ChangeExtension(filename,
349                                         formats.extension("literate") + ".out")));
350
351         // If no Latex log or Build log is newer, show Build log
352
353         FileInfo const f_fi(fname);
354         FileInfo const b_fi(bname);
355
356         if (b_fi.exist() &&
357             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
358                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
359                 return make_pair(Buffer::buildlog, bname);
360         }
361         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
362         return make_pair(Buffer::latexlog, fname);
363 }
364
365
366 void Buffer::setReadonly(bool flag)
367 {
368         if (pimpl_->read_only != flag) {
369                 pimpl_->read_only = flag;
370                 readonly(flag);
371         }
372 }
373
374
375 void Buffer::setFileName(string const & newfile)
376 {
377         pimpl_->filename = MakeAbsPath(newfile);
378         pimpl_->filepath = OnlyPath(pimpl_->filename);
379         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
380         updateTitles();
381 }
382
383
384 // We'll remove this later. (Lgb)
385 namespace {
386
387 void unknownClass(string const & unknown)
388 {
389         Alert::warning(_("Unknown document class"),
390                 bformat(_("Using the default document class, because the "
391                         "class %1$s is unknown."), unknown));
392 }
393
394 } // anon
395
396 int Buffer::readHeader(LyXLex & lex)
397 {
398         int unknown_tokens = 0;
399
400         while (lex.isOK()) {
401                 lex.nextToken();
402                 string const token = lex.getString();
403
404                 if (token.empty())
405                         continue;
406
407                 if (token == "\\end_header")
408                         break;
409
410                 lyxerr[Debug::PARSER] << "Handling header token: `"
411                                       << token << '\'' << endl;
412
413
414                 string unknown = params().readToken(lex, token);
415                 if (!unknown.empty()) {
416                         if (unknown[0] != '\\') {
417                                 unknownClass(unknown);
418                         } else {
419                                 ++unknown_tokens;
420                                 string const s = bformat(_("Unknown token: "
421                                                            "%1$s %2$s\n"),
422                                                          token,
423                                                          lex.getString());
424                                 error(ErrorItem(_("Header error"), s,
425                                                 -1, 0, 0));
426                         }
427                 }
428         }
429         return unknown_tokens;
430 }
431
432
433 // candidate for move to BufferView
434 // (at least some parts in the beginning of the func)
435 //
436 // Uwe C. Schroeder
437 // changed to be public and have one parameter
438 // if par = 0 normal behavior
439 // else insert behavior
440 // Returns false if "\end_document" is not read (Asger)
441 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
442 {
443         Paragraph::depth_type depth = 0;
444         bool the_end_read = false;
445
446         if (paragraphs().empty()) {
447                 readHeader(lex);
448                 if (!params().getLyXTextClass().load()) {
449                         string theclass = params().getLyXTextClass().name();
450                         Alert::error(_("Can't load document class"), bformat(
451                                         "Using the default document class, because the "
452                                         " class %1$s could not be loaded.", theclass));
453                         params().textclass = 0;
454                 }
455         } else {
456                 // We don't want to adopt the parameters from the
457                 // document we insert, so read them into a temporary buffer
458                 // and then discard it
459
460                 Buffer tmpbuf("", false);
461                 tmpbuf.readHeader(lex);
462         }
463
464         while (lex.isOK()) {
465                 lex.nextToken();
466                 string const token = lex.getString();
467
468                 if (token.empty())
469                         continue;
470
471                 lyxerr[Debug::PARSER] << "Handling token: `"
472                                       << token << '\'' << endl;
473
474                 if (token == "\\end_document") {
475                         the_end_read = true;
476                         continue;
477                 }
478
479                 readParagraph(lex, token, paragraphs(), pit, depth);
480         }
481
482         return the_end_read;
483 }
484
485
486 int Buffer::readParagraph(LyXLex & lex, string const & token,
487                           ParagraphList & pars, ParagraphList::iterator & pit,
488                           lyx::depth_type & depth)
489 {
490         static Change current_change;
491         int unknown = 0;
492
493         if (token == "\\begin_layout") {
494                 lex.pushToken(token);
495
496                 Paragraph par;
497                 par.params().depth(depth);
498                 if (params().tracking_changes)
499                         par.trackChanges();
500                 LyXFont f(LyXFont::ALL_INHERIT, params().language);
501                 par.setFont(0, f);
502
503                 // insert after
504                 if (pit != pars.end())
505                         ++pit;
506
507                 pit = pars.insert(pit, par);
508
509                 // FIXME: goddamn InsetTabular makes us pass a Buffer
510                 // not BufferParams
511                 ::readParagraph(*this, *pit, lex);
512
513         } else if (token == "\\begin_deeper") {
514                 ++depth;
515         } else if (token == "\\end_deeper") {
516                 if (!depth) {
517                         lex.printError("\\end_deeper: " "depth is already null");
518                 } else {
519                         --depth;
520                 }
521         } else {
522                 ++unknown;
523         }
524         return unknown;
525 }
526
527
528 // needed to insert the selection
529 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
530                                  LyXFont const & fn,string const & str)
531 {
532         LyXLayout_ptr const & layout = par->layout();
533
534         LyXFont font = fn;
535
536         par->checkInsertChar(font);
537         // insert the string, don't insert doublespace
538         bool space_inserted = true;
539         bool autobreakrows = !par->inInset() ||
540                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
541         for(string::const_iterator cit = str.begin();
542             cit != str.end(); ++cit) {
543                 if (*cit == '\n') {
544                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
545                                 breakParagraph(params(), paragraphs(), par, pos,
546                                                layout->isEnvironment());
547                                 ++par;
548                                 pos = 0;
549                                 space_inserted = true;
550                         } else {
551                                 continue;
552                         }
553                         // do not insert consecutive spaces if !free_spacing
554                 } else if ((*cit == ' ' || *cit == '\t') &&
555                            space_inserted && !par->isFreeSpacing()) {
556                         continue;
557                 } else if (*cit == '\t') {
558                         if (!par->isFreeSpacing()) {
559                                 // tabs are like spaces here
560                                 par->insertChar(pos, ' ', font);
561                                 ++pos;
562                                 space_inserted = true;
563                         } else {
564                                 const pos_type nb = 8 - pos % 8;
565                                 for (pos_type a = 0; a < nb ; ++a) {
566                                         par->insertChar(pos, ' ', font);
567                                         ++pos;
568                                 }
569                                 space_inserted = true;
570                         }
571                 } else if (!IsPrintable(*cit)) {
572                         // Ignore unprintables
573                         continue;
574                 } else {
575                         // just insert the character
576                         par->insertChar(pos, *cit, font);
577                         ++pos;
578                         space_inserted = (*cit == ' ');
579                 }
580
581         }
582 }
583
584
585 bool Buffer::readFile(string const & filename)
586 {
587         // Check if the file is compressed.
588         string const format = getExtFromContents(filename);
589         if (format == "gzip" || format == "zip" || format == "compress") {
590                 params().compressed = true;
591         }
592
593         bool ret = readFile(filename, paragraphs().begin());
594
595         // After we have read a file, we must ensure that the buffer
596         // language is set and used in the gui.
597         // If you know of a better place to put this, please tell me. (Lgb)
598         updateDocLang(params().language);
599
600         return ret;
601 }
602
603
604 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
605 {
606         LyXLex lex(0, 0);
607         lex.setFile(filename);
608
609         return readFile(lex, filename, pit);
610 }
611
612
613 bool Buffer::fully_loaded() const
614 {
615         return pimpl_->file_fully_loaded;
616 }
617
618
619 void Buffer::fully_loaded(bool value)
620 {
621         pimpl_->file_fully_loaded = value;
622 }
623
624
625 bool Buffer::readFile(LyXLex & lex, string const & filename,
626                       ParagraphList::iterator pit)
627 {
628         BOOST_ASSERT(!filename.empty());
629
630         if (!lex.isOK()) {
631                 Alert::error(_("Document could not be read"),
632                              bformat(_("%1$s could not be read."), filename));
633                 return false;
634         }
635
636         lex.next();
637         string const token(lex.getString());
638
639         if (!lex.isOK()) {
640                 Alert::error(_("Document could not be read"),
641                              bformat(_("%1$s could not be read."), filename));
642                 return false;
643         }
644
645         // the first token _must_ be...
646         if (token != "\\lyxformat") {
647                 lyxerr << "Token: " << token << endl;
648
649                 Alert::error(_("Document format failure"),
650                              bformat(_("%1$s is not a LyX document."),
651                                        filename));
652                 return false;
653         }
654
655         lex.eatLine();
656         string tmp_format = lex.getString();
657         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
658         // if present remove ".," from string.
659         string::size_type dot = tmp_format.find_first_of(".,");
660         //lyxerr << "           dot found at " << dot << endl;
661         if (dot != string::npos)
662                         tmp_format.erase(dot, 1);
663         int file_format = strToInt(tmp_format);
664         //lyxerr << "format: " << file_format << endl;
665
666         if (file_format > LYX_FORMAT) {
667                 Alert::warning(_("Document format failure"),
668                                bformat(_("%1$s was created with a newer"
669                                          " version of LyX. This is likely to"
670                                          " cause problems."),
671                                          filename));
672         } else if (file_format < LYX_FORMAT) {
673                 string const tmpfile = tempName();
674                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
675                 if (command.empty()) {
676                         Alert::error(_("Conversion script not found"),
677                                      bformat(_("%1$s is from an earlier"
678                                                " version of LyX, but the"
679                                                " conversion script lyx2lyx"
680                                                " could not be found."),
681                                                filename));
682                         return false;
683                 }
684                 command += " -t"
685                         + tostr(LYX_FORMAT)
686                         + " -o " + tmpfile + ' '
687                         + QuoteName(filename);
688                 lyxerr[Debug::INFO] << "Running '"
689                                     << command << '\''
690                                     << endl;
691                 cmd_ret const ret = RunCommand(command);
692                 if (ret.first != 0) {
693                         Alert::error(_("Conversion script failed"),
694                                      bformat(_("%1$s is from an earlier version"
695                                               " of LyX, but the lyx2lyx script"
696                                               " failed to convert it."),
697                                               filename));
698                         return false;
699                 } else {
700                         bool ret = readFile(tmpfile, pit);
701                         // Do stuff with tmpfile name and buffer name here.
702                         return ret;
703                 }
704
705         }
706
707         bool the_end = readBody(lex, pit);
708         params().setPaperStuff();
709
710         if (!the_end) {
711                 Alert::error(_("Document format failure"),
712                              bformat(_("%1$s ended unexpectedly, which means"
713                                        " that it is probably corrupted."),
714                                        filename));
715         }
716         pimpl_->file_fully_loaded = true;
717         return true;
718 }
719
720
721 // Should probably be moved to somewhere else: BufferView? LyXView?
722 bool Buffer::save() const
723 {
724         // We don't need autosaves in the immediate future. (Asger)
725         resetAutosaveTimers();
726
727         // make a backup
728         string s;
729         if (lyxrc.make_backup) {
730                 s = fileName() + '~';
731                 if (!lyxrc.backupdir_path.empty())
732                         s = AddName(lyxrc.backupdir_path,
733                                     subst(os::slashify_path(s),'/','!'));
734
735                 // Rename is the wrong way of making a backup,
736                 // this is the correct way.
737                 /* truss cp fil fil2:
738                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
739                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
740                    open("LyXVC.lyx", O_RDONLY)                     = 3
741                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
742                    fstat(4, 0xEFFFF508)                            = 0
743                    fstat(3, 0xEFFFF508)                            = 0
744                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
745                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
746                    read(3, 0xEFFFD4A0, 8192)                       = 0
747                    close(4)                                        = 0
748                    close(3)                                        = 0
749                    chmod("LyXVC3.lyx", 0100644)                    = 0
750                    lseek(0, 0, SEEK_CUR)                           = 46440
751                    _exit(0)
752                 */
753
754                 // Should probably have some more error checking here.
755                 // Doing it this way, also makes the inodes stay the same.
756                 // This is still not a very good solution, in particular we
757                 // might loose the owner of the backup.
758                 FileInfo finfo(fileName());
759                 if (finfo.exist()) {
760                         mode_t fmode = finfo.getMode();
761                         struct utimbuf times = {
762                                 finfo.getAccessTime(),
763                                 finfo.getModificationTime() };
764
765                         ifstream ifs(fileName().c_str());
766                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
767                         if (ifs && ofs) {
768                                 ofs << ifs.rdbuf();
769                                 ifs.close();
770                                 ofs.close();
771                                 ::chmod(s.c_str(), fmode);
772
773                                 if (::utime(s.c_str(), &times)) {
774                                         lyxerr << "utime error." << endl;
775                                 }
776                         } else {
777                                 lyxerr << "LyX was not able to make "
778                                         "backup copy. Beware." << endl;
779                         }
780                 }
781         }
782
783         if (writeFile(fileName())) {
784                 markClean();
785                 removeAutosaveFile(fileName());
786         } else {
787                 // Saving failed, so backup is not backup
788                 if (lyxrc.make_backup) {
789                         rename(s, fileName());
790                 }
791                 return false;
792         }
793         return true;
794 }
795
796
797 bool Buffer::writeFile(string const & fname) const
798 {
799         if (pimpl_->read_only && (fname == fileName())) {
800                 return false;
801         }
802
803         FileInfo finfo(fname);
804         if (finfo.exist() && !finfo.writable()) {
805                 return false;
806         }
807
808         bool retval;
809
810         if (params().compressed) {
811                 gz::ogzstream ofs(fname.c_str());
812
813                 if (!ofs)
814                         return false;
815
816                 retval = do_writeFile(ofs);
817
818         } else {
819                 ofstream ofs(fname.c_str());
820                 if (!ofs)
821                         return false;
822
823                 retval = do_writeFile(ofs);
824         }
825
826         return retval;
827 }
828
829
830 bool Buffer::do_writeFile(ostream & ofs) const
831 {
832
833 #ifdef HAVE_LOCALE
834         // Use the standard "C" locale for file output.
835         ofs.imbue(std::locale::classic());
836 #endif
837
838         // The top of the file should not be written by params().
839
840         // write out a comment in the top of the file
841         ofs << "#LyX " << lyx_version
842             << " created this file. For more info see http://www.lyx.org/\n"
843             << "\\lyxformat " << LYX_FORMAT << "\n";
844
845         // now write out the buffer paramters.
846         params().writeFile(ofs);
847
848         ofs << "\\end_header\n";
849
850         Paragraph::depth_type depth = 0;
851
852         // this will write out all the paragraphs
853         // using recursive descent.
854         ParagraphList::const_iterator pit = paragraphs().begin();
855         ParagraphList::const_iterator pend = paragraphs().end();
856         for (; pit != pend; ++pit)
857                 pit->write(*this, ofs, params(), depth);
858
859         // Write marker that shows file is complete
860         ofs << "\n\\end_document" << endl;
861
862         // Shouldn't really be needed....
863         //ofs.close();
864
865         // how to check if close went ok?
866         // Following is an attempt... (BE 20001011)
867
868         // good() returns false if any error occured, including some
869         //        formatting error.
870         // bad()  returns true if something bad happened in the buffer,
871         //        which should include file system full errors.
872
873         bool status = true;
874         if (!ofs.good()) {
875                 status = false;
876 #if 0
877                 if (ofs.bad()) {
878                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
879                 } else {
880                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
881                                << endl;
882                 }
883 #endif
884         }
885
886         return status;
887 }
888
889
890 namespace {
891
892 pair<int, string> const addDepth(int depth, int ldepth)
893 {
894         int d = depth * 2;
895         if (ldepth > depth)
896                 d += (ldepth - depth) * 2;
897         return make_pair(d, string(d, ' '));
898 }
899
900 }
901
902
903 string const Buffer::asciiParagraph(Paragraph const & par,
904                                     unsigned int linelen,
905                                     bool noparbreak) const
906 {
907         ostringstream buffer;
908         int ltype = 0;
909         Paragraph::depth_type ltype_depth = 0;
910         bool ref_printed = false;
911         Paragraph::depth_type depth = par.params().depth();
912
913         // First write the layout
914         string const & tmp = par.layout()->name();
915         if (compare_no_case(tmp, "itemize") == 0) {
916                 ltype = 1;
917                 ltype_depth = depth + 1;
918         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
919                 ltype = 2;
920                 ltype_depth = depth + 1;
921         } else if (contains(ascii_lowercase(tmp), "ection")) {
922                 ltype = 3;
923                 ltype_depth = depth + 1;
924         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
925                 ltype = 4;
926                 ltype_depth = depth + 1;
927         } else if (compare_ascii_no_case(tmp, "description") == 0) {
928                 ltype = 5;
929                 ltype_depth = depth + 1;
930         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
931                 ltype = 6;
932                 ltype_depth = 0;
933         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
934                 ltype = 7;
935                 ltype_depth = 0;
936         } else {
937                 ltype = 0;
938                 ltype_depth = 0;
939         }
940
941         /* maybe some vertical spaces */
942
943         /* the labelwidthstring used in lists */
944
945         /* some lines? */
946
947         /* some pagebreaks? */
948
949         /* noindent ? */
950
951         /* what about the alignment */
952
953         // linelen <= 0 is special and means we don't have paragraph breaks
954
955         string::size_type currlinelen = 0;
956
957         if (!noparbreak) {
958                 if (linelen > 0)
959                         buffer << "\n\n";
960
961                 buffer << string(depth * 2, ' ');
962                 currlinelen += depth * 2;
963
964                 //--
965                 // we should probably change to the paragraph language in the
966                 // gettext here (if possible) so that strings are outputted in
967                 // the correct language! (20012712 Jug)
968                 //--
969                 switch (ltype) {
970                 case 0: // Standard
971                 case 4: // (Sub)Paragraph
972                 case 5: // Description
973                         break;
974                 case 6: // Abstract
975                         if (linelen > 0) {
976                                 buffer << _("Abstract") << "\n\n";
977                                 currlinelen = 0;
978                         } else {
979                                 string const abst = _("Abstract: ");
980                                 buffer << abst;
981                                 currlinelen += abst.length();
982                         }
983                         break;
984                 case 7: // Bibliography
985                         if (!ref_printed) {
986                                 if (linelen > 0) {
987                                         buffer << _("References") << "\n\n";
988                                         currlinelen = 0;
989                                 } else {
990                                         string const refs = _("References: ");
991                                         buffer << refs;
992                                         currlinelen += refs.length();
993                                 }
994
995                                 ref_printed = true;
996                         }
997                         break;
998                 default:
999                 {
1000                         string const parlab = par.params().labelString();
1001                         buffer << parlab << ' ';
1002                         currlinelen += parlab.length() + 1;
1003                 }
1004                 break;
1005
1006                 }
1007         }
1008
1009         if (!currlinelen) {
1010                 pair<int, string> p = addDepth(depth, ltype_depth);
1011                 buffer << p.second;
1012                 currlinelen += p.first;
1013         }
1014
1015         // this is to change the linebreak to do it by word a bit more
1016         // intelligent hopefully! (only in the case where we have a
1017         // max linelength!) (Jug)
1018
1019         string word;
1020
1021         for (pos_type i = 0; i < par.size(); ++i) {
1022                 char c = par.getUChar(params(), i);
1023                 switch (c) {
1024                 case Paragraph::META_INSET:
1025                 {
1026                         InsetOld const * inset = par.getInset(i);
1027                         if (inset) {
1028                                 if (linelen > 0) {
1029                                         buffer << word;
1030                                         currlinelen += word.length();
1031                                         word.erase();
1032                                 }
1033                                 if (inset->ascii(*this, buffer, linelen)) {
1034                                         // to be sure it breaks paragraph
1035                                         currlinelen += linelen;
1036                                 }
1037                         }
1038                 }
1039                 break;
1040
1041                 default:
1042                         if (c == ' ') {
1043                                 if (linelen > 0 &&
1044                                     currlinelen + word.length() > linelen - 10) {
1045                                         buffer << "\n";
1046                                         pair<int, string> p = addDepth(depth, ltype_depth);
1047                                         buffer << p.second;
1048                                         currlinelen = p.first;
1049                                 }
1050
1051                                 buffer << word << ' ';
1052                                 currlinelen += word.length() + 1;
1053                                 word.erase();
1054
1055                         } else {
1056                                 if (c != '\0') {
1057                                         word += c;
1058                                 } else {
1059                                         lyxerr[Debug::INFO] <<
1060                                                 "writeAsciiFile: NULL char in structure." << endl;
1061                                 }
1062                                 if ((linelen > 0) &&
1063                                         (currlinelen + word.length()) > linelen)
1064                                 {
1065                                         buffer << "\n";
1066
1067                                         pair<int, string> p =
1068                                                 addDepth(depth, ltype_depth);
1069                                         buffer << p.second;
1070                                         currlinelen = p.first;
1071                                 }
1072                         }
1073                         break;
1074                 }
1075         }
1076         buffer << word;
1077         return buffer.str();
1078 }
1079
1080
1081 void Buffer::writeFileAscii(string const & fname, int linelen)
1082 {
1083         ofstream ofs;
1084         if (!::openFileWrite(ofs, fname))
1085                 return;
1086         writeFileAscii(ofs, linelen);
1087 }
1088
1089
1090 void Buffer::writeFileAscii(ostream & os, int linelen)
1091 {
1092         ParagraphList::iterator beg = paragraphs().begin();
1093         ParagraphList::iterator end = paragraphs().end();
1094         ParagraphList::iterator it = beg;
1095         for (; it != end; ++it) {
1096                 os << asciiParagraph(*it, linelen, it == beg);
1097         }
1098         os << "\n";
1099 }
1100
1101
1102 void Buffer::makeLaTeXFile(string const & fname,
1103                            string const & original_path,
1104                            LatexRunParams const & runparams,
1105                            bool output_preamble, bool output_body)
1106 {
1107         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1108
1109         ofstream ofs;
1110         if (!::openFileWrite(ofs, fname))
1111                 return;
1112
1113         makeLaTeXFile(ofs, original_path,
1114                       runparams, output_preamble, output_body);
1115
1116         ofs.close();
1117         if (ofs.fail()) {
1118                 lyxerr << "File was not closed properly." << endl;
1119         }
1120 }
1121
1122
1123 void Buffer::makeLaTeXFile(ostream & os,
1124                            string const & original_path,
1125                            LatexRunParams const & runparams_in,
1126                            bool output_preamble, bool output_body)
1127 {
1128         LatexRunParams runparams = runparams_in;
1129         niceFile() = runparams.nice; // this will be used by Insetincludes.
1130
1131         // validate the buffer.
1132         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1133         LaTeXFeatures features(*this, params());
1134         validate(features);
1135         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1136
1137         texrow().reset();
1138         // The starting paragraph of the coming rows is the
1139         // first paragraph of the document. (Asger)
1140         texrow().start(paragraphs().begin()->id(), 0);
1141
1142         if (output_preamble && runparams.nice) {
1143                 os << "%% LyX " << lyx_version << " created this file.  "
1144                         "For more info, see http://www.lyx.org/.\n"
1145                         "%% Do not edit unless you really know what "
1146                         "you are doing.\n";
1147                 texrow().newline();
1148                 texrow().newline();
1149         }
1150         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1151         // There are a few differences between nice LaTeX and usual files:
1152         // usual is \batchmode and has a
1153         // special input@path to allow the including of figures
1154         // with either \input or \includegraphics (what figinsets do).
1155         // input@path is set when the actual parameter
1156         // original_path is set. This is done for usual tex-file, but not
1157         // for nice-latex-file. (Matthias 250696)
1158         if (output_preamble) {
1159                 if (!runparams.nice) {
1160                         // code for usual, NOT nice-latex-file
1161                         os << "\\batchmode\n"; // changed
1162                         // from \nonstopmode
1163                         texrow().newline();
1164                 }
1165                 if (!original_path.empty()) {
1166                         string inputpath = os::external_path(original_path);
1167                         subst(inputpath, "~", "\\string~");
1168                         os << "\\makeatletter\n"
1169                             << "\\def\\input@path{{"
1170                             << inputpath << "/}}\n"
1171                             << "\\makeatother\n";
1172                         texrow().newline();
1173                         texrow().newline();
1174                         texrow().newline();
1175                 }
1176
1177                 // Write the preamble
1178                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1179
1180                 if (!output_body)
1181                         return;
1182
1183                 // make the body.
1184                 os << "\\begin{document}\n";
1185                 texrow().newline();
1186         } // output_preamble
1187         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1188
1189         if (!lyxrc.language_auto_begin) {
1190                 os << subst(lyxrc.language_command_begin, "$$lang",
1191                              params().language->babel())
1192                     << endl;
1193                 texrow().newline();
1194         }
1195
1196         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1197
1198         // add this just in case after all the paragraphs
1199         os << endl;
1200         texrow().newline();
1201
1202         if (!lyxrc.language_auto_end) {
1203                 os << subst(lyxrc.language_command_end, "$$lang",
1204                              params().language->babel())
1205                     << endl;
1206                 texrow().newline();
1207         }
1208
1209         if (output_preamble) {
1210                 os << "\\end{document}\n";
1211                 texrow().newline();
1212
1213                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1214         } else {
1215                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1216                                      << endl;
1217         }
1218
1219         // Just to be sure. (Asger)
1220         texrow().newline();
1221
1222         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1223         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1224                             << '.' << endl;
1225
1226         // we want this to be true outside previews (for insetexternal)
1227         niceFile() = true;
1228 }
1229
1230
1231 bool Buffer::isLatex() const
1232 {
1233         return params().getLyXTextClass().outputType() == LATEX;
1234 }
1235
1236
1237 bool Buffer::isLinuxDoc() const
1238 {
1239         return params().getLyXTextClass().outputType() == LINUXDOC;
1240 }
1241
1242
1243 bool Buffer::isLiterate() const
1244 {
1245         return params().getLyXTextClass().outputType() == LITERATE;
1246 }
1247
1248
1249 bool Buffer::isDocBook() const
1250 {
1251         return params().getLyXTextClass().outputType() == DOCBOOK;
1252 }
1253
1254
1255 bool Buffer::isSGML() const
1256 {
1257         LyXTextClass const & tclass = params().getLyXTextClass();
1258
1259         return tclass.outputType() == LINUXDOC ||
1260                tclass.outputType() == DOCBOOK;
1261 }
1262
1263
1264 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1265 {
1266         ofstream ofs;
1267         if (!::openFileWrite(ofs, fname))
1268                 return;
1269
1270         niceFile() = nice; // this will be used by included files.
1271
1272         LaTeXFeatures features(*this, params());
1273
1274         validate(features);
1275
1276         texrow().reset();
1277
1278         LyXTextClass const & tclass = params().getLyXTextClass();
1279
1280         string top_element = tclass.latexname();
1281
1282         if (!body_only) {
1283                 ofs << "<!doctype linuxdoc system";
1284
1285                 string preamble = params().preamble;
1286                 string const name = nice ? ChangeExtension(pimpl_->filename, ".sgml")
1287                          : fname;
1288                 preamble += features.getIncludedFiles(name);
1289                 preamble += features.getLyXSGMLEntities();
1290
1291                 if (!preamble.empty()) {
1292                         ofs << " [ " << preamble << " ]";
1293                 }
1294                 ofs << ">\n\n";
1295
1296                 if (params().options.empty())
1297                         sgml::openTag(ofs, 0, false, top_element);
1298                 else {
1299                         string top = top_element;
1300                         top += ' ';
1301                         top += params().options;
1302                         sgml::openTag(ofs, 0, false, top);
1303                 }
1304         }
1305
1306         ofs << "<!-- LyX "  << lyx_version
1307             << " created this file. For more info see http://www.lyx.org/"
1308             << " -->\n";
1309
1310         linuxdocParagraphs(*this, paragraphs(), ofs);
1311
1312         if (!body_only) {
1313                 ofs << "\n\n";
1314                 sgml::closeTag(ofs, 0, false, top_element);
1315         }
1316
1317         ofs.close();
1318         // How to check for successful close
1319
1320         // we want this to be true outside previews (for insetexternal)
1321         niceFile() = true;
1322 }
1323
1324
1325 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1326 {
1327         ofstream ofs;
1328         if (!::openFileWrite(ofs, fname))
1329                 return;
1330
1331         niceFile() = nice; // this will be used by Insetincludes.
1332
1333         LaTeXFeatures features(*this, params());
1334         validate(features);
1335
1336         texrow().reset();
1337
1338         LyXTextClass const & tclass = params().getLyXTextClass();
1339         string top_element = tclass.latexname();
1340
1341         if (!only_body) {
1342                 ofs << "<!DOCTYPE " << top_element
1343                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1344
1345                 string preamble = params().preamble;
1346                 string const name = nice ? ChangeExtension(pimpl_->filename, ".sgml")
1347                          : fname;
1348                 preamble += features.getIncludedFiles(name);
1349                 preamble += features.getLyXSGMLEntities();
1350
1351                 if (!preamble.empty()) {
1352                         ofs << "\n [ " << preamble << " ]";
1353                 }
1354                 ofs << ">\n\n";
1355         }
1356
1357         string top = top_element;
1358         top += " lang=\"";
1359         top += params().language->code();
1360         top += '"';
1361
1362         if (!params().options.empty()) {
1363                 top += ' ';
1364                 top += params().options;
1365         }
1366         sgml::openTag(ofs, 0, false, top);
1367
1368         ofs << "<!-- DocBook file was created by LyX " << lyx_version
1369             << "\n  See http://www.lyx.org/ for more information -->\n";
1370
1371         docbookParagraphs(*this, paragraphs(), ofs);
1372
1373         ofs << "\n\n";
1374         sgml::closeTag(ofs, 0, false, top_element);
1375
1376         ofs.close();
1377         // How to check for successful close
1378
1379         // we want this to be true outside previews (for insetexternal)
1380         niceFile() = true;
1381 }
1382
1383
1384 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1385 // Other flags: -wall -v0 -x
1386 int Buffer::runChktex()
1387 {
1388         busy(true);
1389
1390         // get LaTeX-Filename
1391         string const name = getLatexName();
1392         string path = filePath();
1393
1394         string const org_path = path;
1395         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1396                 path = temppath();
1397         }
1398
1399         Path p(path); // path to LaTeX file
1400         message(_("Running chktex..."));
1401
1402         // Generate the LaTeX file if neccessary
1403         LatexRunParams runparams;
1404         runparams.flavor = LatexRunParams::LATEX;
1405         runparams.nice = false;
1406         makeLaTeXFile(name, org_path, runparams);
1407
1408         TeXErrors terr;
1409         Chktex chktex(lyxrc.chktex_command, name, filePath());
1410         int res = chktex.run(terr); // run chktex
1411
1412         if (res == -1) {
1413                 Alert::error(_("chktex failure"),
1414                              _("Could not run chktex successfully."));
1415         } else if (res > 0) {
1416                 // Insert all errors as errors boxes
1417                 bufferErrors(*this, terr);
1418         }
1419
1420         busy(false);
1421
1422         return res;
1423 }
1424
1425
1426 void Buffer::validate(LaTeXFeatures & features) const
1427 {
1428         LyXTextClass const & tclass = params().getLyXTextClass();
1429
1430         if (params().tracking_changes) {
1431                 features.require("dvipost");
1432                 features.require("color");
1433         }
1434
1435         // AMS Style is at document level
1436         if (params().use_amsmath == BufferParams::AMS_ON
1437             || tclass.provides(LyXTextClass::amsmath))
1438                 features.require("amsmath");
1439
1440         for_each(paragraphs().begin(), paragraphs().end(),
1441                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1442
1443         // the bullet shapes are buffer level not paragraph level
1444         // so they are tested here
1445         for (int i = 0; i < 4; ++i) {
1446                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1447                         int const font = params().user_defined_bullet(i).getFont();
1448                         if (font == 0) {
1449                                 int const c = params()
1450                                         .user_defined_bullet(i)
1451                                         .getCharacter();
1452                                 if (c == 16
1453                                    || c == 17
1454                                    || c == 25
1455                                    || c == 26
1456                                    || c == 31) {
1457                                         features.require("latexsym");
1458                                 }
1459                         } else if (font == 1) {
1460                                 features.require("amssymb");
1461                         } else if ((font >= 2 && font <= 5)) {
1462                                 features.require("pifont");
1463                         }
1464                 }
1465         }
1466
1467         if (lyxerr.debugging(Debug::LATEX)) {
1468                 features.showStruct();
1469         }
1470 }
1471
1472
1473 void Buffer::getLabelList(std::vector<string> & list) const
1474 {
1475         /// if this is a child document and the parent is already loaded
1476         /// Use the parent's list instead  [ale990407]
1477         if (!params().parentname.empty()
1478             && bufferlist.exists(params().parentname)) {
1479                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1480                 if (tmp) {
1481                         tmp->getLabelList(list);
1482                         return;
1483                 }
1484         }
1485
1486         for (inset_iterator it = inset_const_iterator_begin();
1487              it != inset_const_iterator_end(); ++it) {
1488                 it->getLabelList(*this, list);
1489         }
1490 }
1491
1492
1493 // This is also a buffer property (ale)
1494 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys) const
1495 {
1496         /// if this is a child document and the parent is already loaded
1497         /// use the parent's list instead  [ale990412]
1498         if (!params().parentname.empty() &&
1499             bufferlist.exists(params().parentname)) {
1500                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1501                 if (tmp) {
1502                         tmp->fillWithBibKeys(keys);
1503                         return;
1504                 }
1505         }
1506
1507         for (inset_iterator it = inset_const_iterator_begin();
1508                 it != inset_const_iterator_end(); ++it) {
1509                 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1510                         InsetBibtex const & inset =
1511                                 dynamic_cast<InsetBibtex const &>(*it);
1512                         inset.fillWithBibKeys(*this, keys);
1513                 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1514                         InsetInclude const & inset =
1515                                 dynamic_cast<InsetInclude const &>(*it);
1516                         inset.fillWithBibKeys(*this, keys);
1517                 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1518                         InsetBibitem const & inset =
1519                                 dynamic_cast<InsetBibitem const &>(*it);
1520                         string const key = inset.getContents();
1521                         string const opt = inset.getOptions();
1522                         string const ref; // = pit->asString(this, false);
1523                         string const info = opt + "TheBibliographyRef" + ref;
1524                         keys.push_back(pair<string, string>(key, info));
1525                 }
1526         }
1527 }
1528
1529
1530 bool Buffer::isDepClean(string const & name) const
1531 {
1532         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1533         if (it == pimpl_->dep_clean.end())
1534                 return true;
1535         return it->second;
1536 }
1537
1538
1539 void Buffer::markDepClean(string const & name)
1540 {
1541         pimpl_->dep_clean[name] = true;
1542 }
1543
1544
1545 bool Buffer::dispatch(string const & command, bool * result)
1546 {
1547         return dispatch(lyxaction.lookupFunc(command), result);
1548 }
1549
1550
1551 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1552 {
1553         bool dispatched = true;
1554
1555         switch (func.action) {
1556                 case LFUN_EXPORT: {
1557                         bool const tmp = Exporter::Export(this, func.argument, false);
1558                         if (result)
1559                                 *result = tmp;
1560                         break;
1561                 }
1562
1563                 default:
1564                         dispatched = false;
1565         }
1566         return dispatched;
1567 }
1568
1569
1570 void Buffer::changeLanguage(Language const * from, Language const * to)
1571 {
1572         lyxerr << "Changing Language!" << endl;
1573
1574         // Take care of l10n/i18n
1575         updateDocLang(to);
1576
1577         ParIterator end = par_iterator_end();
1578         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1579                 it->changeLanguage(params(), from, to);
1580 }
1581
1582
1583 void Buffer::updateDocLang(Language const * nlang)
1584 {
1585         pimpl_->messages.reset(new Messages(nlang->code()));
1586 }
1587
1588
1589 bool Buffer::isMultiLingual()
1590 {
1591         ParIterator end = par_iterator_end();
1592         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1593                 if (it->isMultiLingual(params()))
1594                         return true;
1595
1596         return false;
1597 }
1598
1599
1600 void Buffer::inset_iterator::setParagraph()
1601 {
1602         while (pit != pend) {
1603                 it = pit->insetlist.begin();
1604                 if (it != pit->insetlist.end())
1605                         return;
1606                 ++pit;
1607         }
1608 }
1609
1610
1611 InsetOld * Buffer::getInsetFromID(int id_arg) const
1612 {
1613         for (inset_iterator it = inset_const_iterator_begin();
1614                  it != inset_const_iterator_end(); ++it)
1615         {
1616                 if (it->id() == id_arg)
1617                         return &(*it);
1618                 InsetOld * in = it->getInsetFromID(id_arg);
1619                 if (in)
1620                         return in;
1621         }
1622         return 0;
1623 }
1624
1625
1626 ParIterator Buffer::getParFromID(int id) const
1627 {
1628 #warning FIXME: const correctness! (Andre)
1629         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1630         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1631
1632 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1633         if (id < 0) {
1634                 // John says this is called with id == -1 from undo
1635                 lyxerr << "getParFromID(), id: " << id << endl;
1636                 return end;
1637         }
1638
1639         for (; it != end; ++it)
1640                 if (it->id() == id)
1641                         return it;
1642
1643         return end;
1644 }
1645
1646
1647 bool Buffer::hasParWithID(int id) const
1648 {
1649         ParConstIterator it = par_iterator_begin();
1650         ParConstIterator end = par_iterator_end();
1651
1652         if (id < 0) {
1653                 // John says this is called with id == -1 from undo
1654                 lyxerr << "hasParWithID(), id: " << id << endl;
1655                 return 0;
1656         }
1657
1658         for (; it != end; ++it)
1659                 if (it->id() == id)
1660                         return true;
1661
1662         return false;
1663 }
1664
1665
1666 ParIterator Buffer::par_iterator_begin()
1667 {
1668         return ParIterator(paragraphs().begin(), paragraphs());
1669 }
1670
1671
1672 ParIterator Buffer::par_iterator_end()
1673 {
1674         return ParIterator(paragraphs().end(), paragraphs());
1675 }
1676
1677
1678 ParConstIterator Buffer::par_iterator_begin() const
1679 {
1680         ParagraphList const & pars = paragraphs();
1681         return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
1682 }
1683
1684
1685 ParConstIterator Buffer::par_iterator_end() const
1686 {
1687         ParagraphList const & pars = paragraphs();
1688         return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
1689 }
1690
1691
1692 Language const * Buffer::getLanguage() const
1693 {
1694         return params().language;
1695 }
1696
1697
1698 string const Buffer::B_(string const & l10n) const
1699 {
1700         if (pimpl_->messages.get()) {
1701                 return pimpl_->messages->get(l10n);
1702         }
1703
1704         return _(l10n);
1705 }
1706
1707
1708 bool Buffer::isClean() const
1709 {
1710         return pimpl_->lyx_clean;
1711 }
1712
1713
1714 bool Buffer::isBakClean() const
1715 {
1716         return pimpl_->bak_clean;
1717 }
1718
1719
1720 void Buffer::markClean() const
1721 {
1722         if (!pimpl_->lyx_clean) {
1723                 pimpl_->lyx_clean = true;
1724                 updateTitles();
1725         }
1726         // if the .lyx file has been saved, we don't need an
1727         // autosave
1728         pimpl_->bak_clean = true;
1729 }
1730
1731
1732 void Buffer::markBakClean()
1733 {
1734         pimpl_->bak_clean = true;
1735 }
1736
1737
1738 void Buffer::setUnnamed(bool flag)
1739 {
1740         pimpl_->unnamed = flag;
1741 }
1742
1743
1744 bool Buffer::isUnnamed()
1745 {
1746         return pimpl_->unnamed;
1747 }
1748
1749
1750 void Buffer::markDirty()
1751 {
1752         if (pimpl_->lyx_clean) {
1753                 pimpl_->lyx_clean = false;
1754                 updateTitles();
1755         }
1756         pimpl_->bak_clean = false;
1757
1758         DepClean::iterator it = pimpl_->dep_clean.begin();
1759         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1760
1761         for (; it != end; ++it) {
1762                 it->second = false;
1763         }
1764 }
1765
1766
1767 string const & Buffer::fileName() const
1768 {
1769         return pimpl_->filename;
1770 }
1771
1772
1773 string const & Buffer::filePath() const
1774 {
1775         return pimpl_->filepath;
1776 }
1777
1778
1779 bool Buffer::isReadonly() const
1780 {
1781         return pimpl_->read_only;
1782 }
1783
1784
1785 void Buffer::setParentName(string const & name)
1786 {
1787         params().parentname = name;
1788 }
1789
1790
1791 Buffer::inset_iterator::inset_iterator()
1792         : pit(), pend()
1793 {}
1794
1795
1796 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
1797         : pit(p), pend(e)
1798 {
1799         setParagraph();
1800 }
1801
1802
1803 Buffer::inset_iterator Buffer::inset_iterator_begin()
1804 {
1805         return inset_iterator(paragraphs().begin(), paragraphs().end());
1806 }
1807
1808
1809 Buffer::inset_iterator Buffer::inset_iterator_end()
1810 {
1811         return inset_iterator(paragraphs().end(), paragraphs().end());
1812 }
1813
1814
1815 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1816 {
1817         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1818         return inset_iterator(pars.begin(), pars.end());
1819 }
1820
1821
1822 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1823 {
1824         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1825         return inset_iterator(pars.end(), pars.end());
1826 }
1827
1828
1829 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1830 {
1831         if (pit != pend) {
1832                 ++it;
1833                 if (it == pit->insetlist.end()) {
1834                         ++pit;
1835                         setParagraph();
1836                 }
1837         }
1838         return *this;
1839 }
1840
1841
1842 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1843 {
1844         inset_iterator tmp = *this;
1845         ++*this;
1846         return tmp;
1847 }
1848
1849
1850 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1851 {
1852         return *it->inset;
1853 }
1854
1855
1856 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1857 {
1858         return it->inset;
1859 }
1860
1861
1862 ParagraphList::iterator Buffer::inset_iterator::getPar() const
1863 {
1864         return pit;
1865 }
1866
1867
1868 lyx::pos_type Buffer::inset_iterator::getPos() const
1869 {
1870         return it->pos;
1871 }
1872
1873
1874 bool operator==(Buffer::inset_iterator const & iter1,
1875                 Buffer::inset_iterator const & iter2)
1876 {
1877         return iter1.pit == iter2.pit
1878                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
1879 }
1880
1881
1882 bool operator!=(Buffer::inset_iterator const & iter1,
1883                 Buffer::inset_iterator const & iter2)
1884 {
1885         return !(iter1 == iter2);
1886 }