]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Small clean-up.
[lyx.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 "gettext.h"
26 #include "iterators.h"
27 #include "language.h"
28 #include "LaTeX.h"
29 #include "LaTeXFeatures.h"
30 #include "LyXAction.h"
31 #include "lyxlex.h"
32 #include "lyxrc.h"
33 #include "lyxvc.h"
34 #include "messages.h"
35 #include "paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "sgml.h"
39 #include "texrow.h"
40 #include "undo.h"
41 #include "version.h"
42
43 #include "insets/insetbibitem.h"
44 #include "insets/insetbibtex.h"
45 #include "insets/insetinclude.h"
46 #include "insets/insettext.h"
47
48 #include "frontends/Alert.h"
49
50 #include "graphics/Previews.h"
51
52 #include "support/FileInfo.h"
53 #include "support/filetools.h"
54 #include "support/gzstream.h"
55 #include "support/lyxlib.h"
56 #include "support/os.h"
57 #include "support/path.h"
58 #include "support/textutils.h"
59 #include "support/tostr.h"
60
61 #include <boost/bind.hpp>
62 #include <boost/tuple/tuple.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::list;
118 using std::ios;
119 using std::ostream;
120 using std::ostringstream;
121 using std::ofstream;
122 using std::pair;
123 using std::stack;
124 using std::vector;
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
189
190 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
191         : nicefile(true),
192           lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
193           filename(file), filepath(OnlyPath(file))
194 {
195         lyxvc.buffer(&parent);
196         if (readonly_ || lyxrc.use_tempdir)
197                 temppath = CreateBufferTmpDir();
198 }
199
200
201 Buffer::Buffer(string const & file, bool ronly)
202         : pimpl_(new Impl(*this, file, ronly))
203 {
204         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
205 }
206
207
208 Buffer::~Buffer()
209 {
210         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
211         // here the buffer should take care that it is
212         // saved properly, before it goes into the void.
213
214         closing();
215
216         if (!temppath().empty() && destroyDir(temppath()) != 0) {
217                 Alert::warning(_("Could not remove temporary directory"),
218                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
219         }
220
221         paragraphs().clear();
222
223         // Remove any previewed LaTeX snippets associated with this buffer.
224         lyx::graphics::Previews::get().removeLoader(*this);
225 }
226
227
228 limited_stack<Undo> & Buffer::undostack()
229 {
230         return pimpl_->undostack;
231 }
232
233
234 limited_stack<Undo> const & Buffer::undostack() const
235 {
236         return pimpl_->undostack;
237 }
238
239
240 limited_stack<Undo> & Buffer::redostack()
241 {
242         return pimpl_->redostack;
243 }
244
245
246 limited_stack<Undo> const & Buffer::redostack() const
247 {
248         return pimpl_->redostack;
249 }
250
251
252 BufferParams & Buffer::params()
253 {
254         return pimpl_->params;
255 }
256
257
258 BufferParams const & Buffer::params() const
259 {
260         return pimpl_->params;
261 }
262
263
264 ParagraphList & Buffer::paragraphs()
265 {
266         return pimpl_->paragraphs;
267 }
268
269
270 ParagraphList const & Buffer::paragraphs() const
271 {
272         return pimpl_->paragraphs;
273 }
274
275
276 LyXVC & Buffer::lyxvc()
277 {
278         return pimpl_->lyxvc;
279 }
280
281
282 LyXVC const & Buffer::lyxvc() const
283 {
284         return pimpl_->lyxvc;
285 }
286
287
288 string const & Buffer::temppath() const
289 {
290         return pimpl_->temppath;
291 }
292
293
294 bool & Buffer::niceFile()
295 {
296         return pimpl_->nicefile;
297 }
298
299
300 bool Buffer::niceFile() const
301 {
302         return pimpl_->nicefile;
303 }
304
305
306 TexRow & Buffer::texrow()
307 {
308         return pimpl_->texrow;
309 }
310
311
312 TexRow const & Buffer::texrow() const
313 {
314         return pimpl_->texrow;
315 }
316
317
318 string const Buffer::getLatexName(bool no_path) const
319 {
320         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
321         return no_path ? OnlyFilename(name) : name;
322 }
323
324
325 pair<Buffer::LogType, string> const Buffer::getLogName() const
326 {
327         string const filename = getLatexName(false);
328
329         if (filename.empty())
330                 return make_pair(Buffer::latexlog, string());
331
332         string path = OnlyPath(filename);
333
334         if (lyxrc.use_tempdir || !IsDirWriteable(path))
335                 path = temppath();
336
337         string const fname = AddName(path,
338                                      OnlyFilename(ChangeExtension(filename,
339                                                                   ".log")));
340         string const bname =
341                 AddName(path, OnlyFilename(
342                         ChangeExtension(filename,
343                                         formats.extension("literate") + ".out")));
344
345         // If no Latex log or Build log is newer, show Build log
346
347         FileInfo const f_fi(fname);
348         FileInfo const b_fi(bname);
349
350         if (b_fi.exist() &&
351             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
352                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
353                 return make_pair(Buffer::buildlog, bname);
354         }
355         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
356         return make_pair(Buffer::latexlog, fname);
357 }
358
359
360 void Buffer::setReadonly(bool flag)
361 {
362         if (pimpl_->read_only != flag) {
363                 pimpl_->read_only = flag;
364                 readonly(flag);
365         }
366 }
367
368
369 void Buffer::setFileName(string const & newfile)
370 {
371         pimpl_->filename = MakeAbsPath(newfile);
372         pimpl_->filepath = OnlyPath(pimpl_->filename);
373         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
374         updateTitles();
375 }
376
377
378 // We'll remove this later. (Lgb)
379 namespace {
380
381 void unknownClass(string const & unknown)
382 {
383         Alert::warning(_("Unknown document class"),
384                 bformat(_("Using the default document class, because the "
385                         "class %1$s is unknown."), unknown));
386 }
387
388 } // anon
389
390 int Buffer::readHeader(LyXLex & lex)
391 {
392         int unknown_tokens = 0;
393
394         while (lex.isOK()) {
395                 lex.nextToken();
396                 string const token = lex.getString();
397
398                 if (token.empty())
399                         continue;
400
401                 if (token == "\\end_header")
402                         break;
403
404                 lyxerr[Debug::PARSER] << "Handling header token: `"
405                                       << token << '\'' << endl;
406
407
408                 string unknown = params().readToken(lex, token);
409                 if (!unknown.empty()) {
410                         if (unknown[0] != '\\') {
411                                 unknownClass(unknown);
412                         } else {
413                                 ++unknown_tokens;
414                                 string const s = bformat(_("Unknown token: "
415                                                            "%1$s %2$s\n"),
416                                                          token,
417                                                          lex.getString());
418                                 error(ErrorItem(_("Header error"), s,
419                                                 -1, 0, 0));
420                         }
421                 }
422         }
423         return unknown_tokens;
424 }
425
426
427 // candidate for move to BufferView
428 // (at least some parts in the beginning of the func)
429 //
430 // Uwe C. Schroeder
431 // changed to be public and have one parameter
432 // if par = 0 normal behavior
433 // else insert behavior
434 // Returns false if "\end_document" is not read (Asger)
435 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
436 {
437         Paragraph::depth_type depth = 0;
438         bool the_end_read = false;
439
440         if (paragraphs().empty()) {
441                 readHeader(lex);
442                 if (!params().getLyXTextClass().load()) {
443                         string theclass = params().getLyXTextClass().name();
444                         Alert::error(_("Can't load document class"), bformat(
445                                         "Using the default document class, because the "
446                                         " class %1$s could not be loaded.", theclass));
447                         params().textclass = 0;
448                 }
449         } else {
450                 // We don't want to adopt the parameters from the
451                 // document we insert, so read them into a temporary buffer
452                 // and then discard it
453
454                 Buffer tmpbuf("", false);
455                 tmpbuf.readHeader(lex);
456         }
457
458         while (lex.isOK()) {
459                 lex.nextToken();
460                 string const token = lex.getString();
461
462                 if (token.empty())
463                         continue;
464
465                 lyxerr[Debug::PARSER] << "Handling token: `"
466                                       << token << '\'' << endl;
467
468                 if (token == "\\end_document") {
469                         the_end_read = true;
470                         continue;
471                 }
472
473                 readParagraph(lex, token, paragraphs(), pit, depth);
474         }
475
476         return the_end_read;
477 }
478
479
480 int Buffer::readParagraph(LyXLex & lex, string const & token,
481                           ParagraphList & pars, ParagraphList::iterator & pit,
482                           Paragraph::depth_type & depth)
483 {
484         static Change current_change;
485         int unknown = 0;
486
487         if (token == "\\begin_layout") {
488                 lex.pushToken(token);
489
490                 Paragraph par;
491                 par.params().depth(depth);
492                 if (params().tracking_changes)
493                         par.trackChanges();
494                 LyXFont f(LyXFont::ALL_INHERIT, params().language);
495                 par.setFont(0, f);
496
497                 // insert after
498                 if (pit != pars.end())
499                         ++pit;
500
501                 pit = pars.insert(pit, par);
502
503                 // FIXME: goddamn InsetTabular makes us pass a Buffer
504                 // not BufferParams
505                 ::readParagraph(*this, *pit, lex);
506
507         } else if (token == "\\begin_deeper") {
508                 ++depth;
509         } else if (token == "\\end_deeper") {
510                 if (!depth) {
511                         lex.printError("\\end_deeper: " "depth is already null");
512                 } else {
513                         --depth;
514                 }
515         } else {
516                 ++unknown;
517         }
518         return unknown;
519 }
520
521
522 // needed to insert the selection
523 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
524                                  LyXFont const & fn,string const & str)
525 {
526         LyXLayout_ptr const & layout = par->layout();
527
528         LyXFont font = fn;
529
530         par->checkInsertChar(font);
531         // insert the string, don't insert doublespace
532         bool space_inserted = true;
533         bool autobreakrows = !par->inInset() ||
534                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
535         for(string::const_iterator cit = str.begin();
536             cit != str.end(); ++cit) {
537                 if (*cit == '\n') {
538                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
539                                 breakParagraph(params(), paragraphs(), par, pos,
540                                                layout->isEnvironment());
541                                 ++par;
542                                 pos = 0;
543                                 space_inserted = true;
544                         } else {
545                                 continue;
546                         }
547                         // do not insert consecutive spaces if !free_spacing
548                 } else if ((*cit == ' ' || *cit == '\t') &&
549                            space_inserted && !par->isFreeSpacing()) {
550                         continue;
551                 } else if (*cit == '\t') {
552                         if (!par->isFreeSpacing()) {
553                                 // tabs are like spaces here
554                                 par->insertChar(pos, ' ', font);
555                                 ++pos;
556                                 space_inserted = true;
557                         } else {
558                                 const pos_type nb = 8 - pos % 8;
559                                 for (pos_type a = 0; a < nb ; ++a) {
560                                         par->insertChar(pos, ' ', font);
561                                         ++pos;
562                                 }
563                                 space_inserted = true;
564                         }
565                 } else if (!IsPrintable(*cit)) {
566                         // Ignore unprintables
567                         continue;
568                 } else {
569                         // just insert the character
570                         par->insertChar(pos, *cit, font);
571                         ++pos;
572                         space_inserted = (*cit == ' ');
573                 }
574
575         }
576 }
577
578
579 bool Buffer::readFile(string const & filename)
580 {
581         // Check if the file is compressed.
582         string const format = getExtFromContents(filename);
583         if (format == "gzip" || format == "zip" || format == "compress") {
584                 params().compressed = true;
585         }
586
587         bool ret = readFile(filename, paragraphs().begin());
588
589         // After we have read a file, we must ensure that the buffer
590         // language is set and used in the gui.
591         // If you know of a better place to put this, please tell me. (Lgb)
592         updateDocLang(params().language);
593
594         return ret;
595 }
596
597
598 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
599 {
600         LyXLex lex(0, 0);
601         lex.setFile(filename);
602
603         return readFile(lex, filename, pit);
604 }
605
606
607 bool Buffer::readFile(LyXLex & lex, string const & filename,
608                       ParagraphList::iterator pit)
609 {
610         BOOST_ASSERT(!filename.empty());
611
612         if (!lex.isOK()) {
613                 Alert::error(_("Document could not be read"),
614                              bformat(_("%1$s could not be read."), filename));
615                 return false;
616         }
617
618         lex.next();
619         string const token(lex.getString());
620
621         if (!lex.isOK()) {
622                 Alert::error(_("Document could not be read"),
623                              bformat(_("%1$s could not be read."), filename));
624                 return false;
625         }
626
627         // the first token _must_ be...
628         if (token != "\\lyxformat") {
629                 lyxerr << "Token: " << token << endl;
630
631                 Alert::error(_("Document format failure"),
632                              bformat(_("%1$s is not a LyX document."),
633                                        filename));
634                 return false;
635         }
636
637         lex.eatLine();
638         string tmp_format = lex.getString();
639         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
640         // if present remove ".," from string.
641         string::size_type dot = tmp_format.find_first_of(".,");
642         //lyxerr << "           dot found at " << dot << endl;
643         if (dot != string::npos)
644                         tmp_format.erase(dot, 1);
645         int file_format = strToInt(tmp_format);
646         //lyxerr << "format: " << file_format << endl;
647
648         if (file_format > LYX_FORMAT) {
649                 Alert::warning(_("Document format failure"),
650                                bformat(_("%1$s was created with a newer"
651                                          " version of LyX. This is likely to"
652                                          " cause problems."),
653                                          filename));
654         } else if (file_format < LYX_FORMAT) {
655                 string const tmpfile = tempName();
656                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
657                 if (command.empty()) {
658                         Alert::error(_("Conversion script not found"),
659                                      bformat(_("%1$s is from an earlier"
660                                                " version of LyX, but the"
661                                                " conversion script lyx2lyx"
662                                                " could not be found."),
663                                                filename));
664                         return false;
665                 }
666                 command += " -t"
667                         + tostr(LYX_FORMAT)
668                         + " -o " + tmpfile + ' '
669                         + QuoteName(filename);
670                 lyxerr[Debug::INFO] << "Running '"
671                                     << command << '\''
672                                     << endl;
673                 cmd_ret const ret = RunCommand(command);
674                 if (ret.first != 0) {
675                         Alert::error(_("Conversion script failed"),
676                                      bformat(_("%1$s is from an earlier version"
677                                               " of LyX, but the lyx2lyx script"
678                                               " failed to convert it."),
679                                               filename));
680                         return false;
681                 } else {
682                         bool ret = readFile(tmpfile, pit);
683                         // Do stuff with tmpfile name and buffer name here.
684                         return ret;
685                 }
686
687         }
688
689         bool the_end = readBody(lex, pit);
690         params().setPaperStuff();
691
692         if (!the_end) {
693                 Alert::error(_("Document format failure"),
694                              bformat(_("%1$s ended unexpectedly, which means"
695                                        " that it is probably corrupted."),
696                                        filename));
697         }
698         return true;
699 }
700
701
702 // Should probably be moved to somewhere else: BufferView? LyXView?
703 bool Buffer::save() const
704 {
705         // We don't need autosaves in the immediate future. (Asger)
706         resetAutosaveTimers();
707
708         // make a backup
709         string s;
710         if (lyxrc.make_backup) {
711                 s = fileName() + '~';
712                 if (!lyxrc.backupdir_path.empty())
713                         s = AddName(lyxrc.backupdir_path,
714                                     subst(os::slashify_path(s),'/','!'));
715
716                 // Rename is the wrong way of making a backup,
717                 // this is the correct way.
718                 /* truss cp fil fil2:
719                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
720                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
721                    open("LyXVC.lyx", O_RDONLY)                     = 3
722                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
723                    fstat(4, 0xEFFFF508)                            = 0
724                    fstat(3, 0xEFFFF508)                            = 0
725                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
726                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
727                    read(3, 0xEFFFD4A0, 8192)                       = 0
728                    close(4)                                        = 0
729                    close(3)                                        = 0
730                    chmod("LyXVC3.lyx", 0100644)                    = 0
731                    lseek(0, 0, SEEK_CUR)                           = 46440
732                    _exit(0)
733                 */
734
735                 // Should probably have some more error checking here.
736                 // Doing it this way, also makes the inodes stay the same.
737                 // This is still not a very good solution, in particular we
738                 // might loose the owner of the backup.
739                 FileInfo finfo(fileName());
740                 if (finfo.exist()) {
741                         mode_t fmode = finfo.getMode();
742                         struct utimbuf times = {
743                                 finfo.getAccessTime(),
744                                 finfo.getModificationTime() };
745
746                         ifstream ifs(fileName().c_str());
747                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
748                         if (ifs && ofs) {
749                                 ofs << ifs.rdbuf();
750                                 ifs.close();
751                                 ofs.close();
752                                 ::chmod(s.c_str(), fmode);
753
754                                 if (::utime(s.c_str(), &times)) {
755                                         lyxerr << "utime error." << endl;
756                                 }
757                         } else {
758                                 lyxerr << "LyX was not able to make "
759                                         "backup copy. Beware." << endl;
760                         }
761                 }
762         }
763
764         if (writeFile(fileName())) {
765                 markClean();
766                 removeAutosaveFile(fileName());
767         } else {
768                 // Saving failed, so backup is not backup
769                 if (lyxrc.make_backup) {
770                         rename(s, fileName());
771                 }
772                 return false;
773         }
774         return true;
775 }
776
777
778 bool Buffer::writeFile(string const & fname) const
779 {
780         if (pimpl_->read_only && (fname == fileName())) {
781                 return false;
782         }
783
784         FileInfo finfo(fname);
785         if (finfo.exist() && !finfo.writable()) {
786                 return false;
787         }
788
789         bool retval;
790
791         if (params().compressed) {
792                 gz::ogzstream ofs(fname.c_str());
793
794                 if (!ofs)
795                         return false;
796
797                 retval = do_writeFile(ofs);
798
799         } else {
800                 ofstream ofs(fname.c_str());
801                 if (!ofs)
802                         return false;
803
804                 retval = do_writeFile(ofs);
805         }
806
807         return retval;
808 }
809
810
811 bool Buffer::do_writeFile(ostream & ofs) const
812 {
813
814 #ifdef HAVE_LOCALE
815         // Use the standard "C" locale for file output.
816         ofs.imbue(std::locale::classic());
817 #endif
818
819         // The top of the file should not be written by params().
820
821         // write out a comment in the top of the file
822         ofs << "#LyX " << lyx_version
823             << " created this file. For more info see http://www.lyx.org/\n"
824             << "\\lyxformat " << LYX_FORMAT << "\n";
825
826         // now write out the buffer paramters.
827         params().writeFile(ofs);
828
829         ofs << "\\end_header\n";
830
831         Paragraph::depth_type depth = 0;
832
833         // this will write out all the paragraphs
834         // using recursive descent.
835         ParagraphList::const_iterator pit = paragraphs().begin();
836         ParagraphList::const_iterator pend = paragraphs().end();
837         for (; pit != pend; ++pit)
838                 pit->write(*this, ofs, params(), depth);
839
840         // Write marker that shows file is complete
841         ofs << "\n\\end_document" << endl;
842
843         // Shouldn't really be needed....
844         //ofs.close();
845
846         // how to check if close went ok?
847         // Following is an attempt... (BE 20001011)
848
849         // good() returns false if any error occured, including some
850         //        formatting error.
851         // bad()  returns true if something bad happened in the buffer,
852         //        which should include file system full errors.
853
854         bool status = true;
855         if (!ofs.good()) {
856                 status = false;
857 #if 0
858                 if (ofs.bad()) {
859                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
860                 } else {
861                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
862                                << endl;
863                 }
864 #endif
865         }
866
867         return status;
868 }
869
870
871 namespace {
872
873 pair<int, string> const addDepth(int depth, int ldepth)
874 {
875         int d = depth * 2;
876         if (ldepth > depth)
877                 d += (ldepth - depth) * 2;
878         return make_pair(d, string(d, ' '));
879 }
880
881 }
882
883
884 string const Buffer::asciiParagraph(Paragraph const & par,
885                                     unsigned int linelen,
886                                     bool noparbreak) const
887 {
888         ostringstream buffer;
889         int ltype = 0;
890         Paragraph::depth_type ltype_depth = 0;
891         bool ref_printed = false;
892         Paragraph::depth_type depth = par.params().depth();
893
894         // First write the layout
895         string const & tmp = par.layout()->name();
896         if (compare_no_case(tmp, "itemize") == 0) {
897                 ltype = 1;
898                 ltype_depth = depth + 1;
899         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
900                 ltype = 2;
901                 ltype_depth = depth + 1;
902         } else if (contains(ascii_lowercase(tmp), "ection")) {
903                 ltype = 3;
904                 ltype_depth = depth + 1;
905         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
906                 ltype = 4;
907                 ltype_depth = depth + 1;
908         } else if (compare_ascii_no_case(tmp, "description") == 0) {
909                 ltype = 5;
910                 ltype_depth = depth + 1;
911         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
912                 ltype = 6;
913                 ltype_depth = 0;
914         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
915                 ltype = 7;
916                 ltype_depth = 0;
917         } else {
918                 ltype = 0;
919                 ltype_depth = 0;
920         }
921
922         /* maybe some vertical spaces */
923
924         /* the labelwidthstring used in lists */
925
926         /* some lines? */
927
928         /* some pagebreaks? */
929
930         /* noindent ? */
931
932         /* what about the alignment */
933
934         // linelen <= 0 is special and means we don't have paragraph breaks
935
936         string::size_type currlinelen = 0;
937
938         if (!noparbreak) {
939                 if (linelen > 0)
940                         buffer << "\n\n";
941
942                 buffer << string(depth * 2, ' ');
943                 currlinelen += depth * 2;
944
945                 //--
946                 // we should probably change to the paragraph language in the
947                 // gettext here (if possible) so that strings are outputted in
948                 // the correct language! (20012712 Jug)
949                 //--
950                 switch (ltype) {
951                 case 0: // Standard
952                 case 4: // (Sub)Paragraph
953                 case 5: // Description
954                         break;
955                 case 6: // Abstract
956                         if (linelen > 0) {
957                                 buffer << _("Abstract") << "\n\n";
958                                 currlinelen = 0;
959                         } else {
960                                 string const abst = _("Abstract: ");
961                                 buffer << abst;
962                                 currlinelen += abst.length();
963                         }
964                         break;
965                 case 7: // Bibliography
966                         if (!ref_printed) {
967                                 if (linelen > 0) {
968                                         buffer << _("References") << "\n\n";
969                                         currlinelen = 0;
970                                 } else {
971                                         string const refs = _("References: ");
972                                         buffer << refs;
973                                         currlinelen += refs.length();
974                                 }
975
976                                 ref_printed = true;
977                         }
978                         break;
979                 default:
980                 {
981                         string const parlab = par.params().labelString();
982                         buffer << parlab << ' ';
983                         currlinelen += parlab.length() + 1;
984                 }
985                 break;
986
987                 }
988         }
989
990         if (!currlinelen) {
991                 pair<int, string> p = addDepth(depth, ltype_depth);
992                 buffer << p.second;
993                 currlinelen += p.first;
994         }
995
996         // this is to change the linebreak to do it by word a bit more
997         // intelligent hopefully! (only in the case where we have a
998         // max linelength!) (Jug)
999
1000         string word;
1001
1002         for (pos_type i = 0; i < par.size(); ++i) {
1003                 char c = par.getUChar(params(), i);
1004                 switch (c) {
1005                 case Paragraph::META_INSET:
1006                 {
1007                         InsetOld const * inset = par.getInset(i);
1008                         if (inset) {
1009                                 if (linelen > 0) {
1010                                         buffer << word;
1011                                         currlinelen += word.length();
1012                                         word.erase();
1013                                 }
1014                                 if (inset->ascii(*this, buffer, linelen)) {
1015                                         // to be sure it breaks paragraph
1016                                         currlinelen += linelen;
1017                                 }
1018                         }
1019                 }
1020                 break;
1021
1022                 default:
1023                         if (c == ' ') {
1024                                 if (linelen > 0 &&
1025                                     currlinelen + word.length() > linelen - 10) {
1026                                         buffer << "\n";
1027                                         pair<int, string> p = addDepth(depth, ltype_depth);
1028                                         buffer << p.second;
1029                                         currlinelen = p.first;
1030                                 }
1031
1032                                 buffer << word << ' ';
1033                                 currlinelen += word.length() + 1;
1034                                 word.erase();
1035
1036                         } else {
1037                                 if (c != '\0') {
1038                                         word += c;
1039                                 } else {
1040                                         lyxerr[Debug::INFO] <<
1041                                                 "writeAsciiFile: NULL char in structure." << endl;
1042                                 }
1043                                 if ((linelen > 0) &&
1044                                         (currlinelen + word.length()) > linelen)
1045                                 {
1046                                         buffer << "\n";
1047
1048                                         pair<int, string> p =
1049                                                 addDepth(depth, ltype_depth);
1050                                         buffer << p.second;
1051                                         currlinelen = p.first;
1052                                 }
1053                         }
1054                         break;
1055                 }
1056         }
1057         buffer << word;
1058         return buffer.str();
1059 }
1060
1061
1062 void Buffer::writeFileAscii(string const & fname, int linelen)
1063 {
1064         ofstream ofs;
1065         if (!::openFileWrite(ofs, fname))
1066                 return;
1067         writeFileAscii(ofs, linelen);
1068 }
1069
1070
1071 void Buffer::writeFileAscii(ostream & os, int linelen)
1072 {
1073         ParagraphList::iterator beg = paragraphs().begin();
1074         ParagraphList::iterator end = paragraphs().end();
1075         ParagraphList::iterator it = beg;
1076         for (; it != end; ++it) {
1077                 os << asciiParagraph(*it, linelen, it == beg);
1078         }
1079         os << "\n";
1080 }
1081
1082
1083 void Buffer::makeLaTeXFile(string const & fname,
1084                            string const & original_path,
1085                            LatexRunParams const & runparams,
1086                            bool output_preamble, bool output_body)
1087 {
1088         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1089
1090         ofstream ofs;
1091         if (!::openFileWrite(ofs, fname))
1092                 return;
1093
1094         makeLaTeXFile(ofs, original_path,
1095                       runparams, output_preamble, output_body);
1096
1097         ofs.close();
1098         if (ofs.fail()) {
1099                 lyxerr << "File was not closed properly." << endl;
1100         }
1101 }
1102
1103
1104 void Buffer::makeLaTeXFile(ostream & os,
1105                            string const & original_path,
1106                            LatexRunParams const & runparams_in,
1107                            bool output_preamble, bool output_body)
1108 {
1109         LatexRunParams runparams = runparams_in;
1110         niceFile() = runparams.nice; // this will be used by Insetincludes.
1111
1112         // validate the buffer.
1113         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1114         LaTeXFeatures features(*this, params());
1115         validate(features);
1116         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1117
1118         texrow().reset();
1119         // The starting paragraph of the coming rows is the
1120         // first paragraph of the document. (Asger)
1121         texrow().start(paragraphs().begin()->id(), 0);
1122
1123         if (output_preamble && runparams.nice) {
1124                 os << "%% LyX " << lyx_version << " created this file.  "
1125                         "For more info, see http://www.lyx.org/.\n"
1126                         "%% Do not edit unless you really know what "
1127                         "you are doing.\n";
1128                 texrow().newline();
1129                 texrow().newline();
1130         }
1131         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1132         // There are a few differences between nice LaTeX and usual files:
1133         // usual is \batchmode and has a
1134         // special input@path to allow the including of figures
1135         // with either \input or \includegraphics (what figinsets do).
1136         // input@path is set when the actual parameter
1137         // original_path is set. This is done for usual tex-file, but not
1138         // for nice-latex-file. (Matthias 250696)
1139         if (output_preamble) {
1140                 if (!runparams.nice) {
1141                         // code for usual, NOT nice-latex-file
1142                         os << "\\batchmode\n"; // changed
1143                         // from \nonstopmode
1144                         texrow().newline();
1145                 }
1146                 if (!original_path.empty()) {
1147                         string inputpath = os::external_path(original_path);
1148                         subst(inputpath, "~", "\\string~");
1149                         os << "\\makeatletter\n"
1150                             << "\\def\\input@path{{"
1151                             << inputpath << "/}}\n"
1152                             << "\\makeatother\n";
1153                         texrow().newline();
1154                         texrow().newline();
1155                         texrow().newline();
1156                 }
1157
1158                 // Write the preamble
1159                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1160
1161                 if (!output_body)
1162                         return;
1163
1164                 // make the body.
1165                 os << "\\begin{document}\n";
1166                 texrow().newline();
1167         } // output_preamble
1168         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1169
1170         if (!lyxrc.language_auto_begin) {
1171                 os << subst(lyxrc.language_command_begin, "$$lang",
1172                              params().language->babel())
1173                     << endl;
1174                 texrow().newline();
1175         }
1176
1177         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1178
1179         // add this just in case after all the paragraphs
1180         os << endl;
1181         texrow().newline();
1182
1183         if (!lyxrc.language_auto_end) {
1184                 os << subst(lyxrc.language_command_end, "$$lang",
1185                              params().language->babel())
1186                     << endl;
1187                 texrow().newline();
1188         }
1189
1190         if (output_preamble) {
1191                 os << "\\end{document}\n";
1192                 texrow().newline();
1193
1194                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1195         } else {
1196                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1197                                      << endl;
1198         }
1199
1200         // Just to be sure. (Asger)
1201         texrow().newline();
1202
1203         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1204         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1205                             << '.' << endl;
1206
1207         // we want this to be true outside previews (for insetexternal)
1208         niceFile() = true;
1209 }
1210
1211
1212 bool Buffer::isLatex() const
1213 {
1214         return params().getLyXTextClass().outputType() == LATEX;
1215 }
1216
1217
1218 bool Buffer::isLinuxDoc() const
1219 {
1220         return params().getLyXTextClass().outputType() == LINUXDOC;
1221 }
1222
1223
1224 bool Buffer::isLiterate() const
1225 {
1226         return params().getLyXTextClass().outputType() == LITERATE;
1227 }
1228
1229
1230 bool Buffer::isDocBook() const
1231 {
1232         return params().getLyXTextClass().outputType() == DOCBOOK;
1233 }
1234
1235
1236 bool Buffer::isSGML() const
1237 {
1238         LyXTextClass const & tclass = params().getLyXTextClass();
1239
1240         return tclass.outputType() == LINUXDOC ||
1241                tclass.outputType() == DOCBOOK;
1242 }
1243
1244
1245 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1246 {
1247         ofstream ofs;
1248         if (!::openFileWrite(ofs, fname))
1249                 return;
1250
1251         niceFile() = nice; // this will be used by included files.
1252
1253         LaTeXFeatures features(*this, params());
1254
1255         validate(features);
1256
1257         texrow().reset();
1258
1259         LyXTextClass const & tclass = params().getLyXTextClass();
1260
1261         string top_element = tclass.latexname();
1262
1263         if (!body_only) {
1264                 ofs << "<!doctype linuxdoc system";
1265
1266                 string preamble = params().preamble;
1267                 string const name = nice ? ChangeExtension(pimpl_->filename, ".sgml")
1268                          : fname;
1269                 preamble += features.getIncludedFiles(name);
1270                 preamble += features.getLyXSGMLEntities();
1271
1272                 if (!preamble.empty()) {
1273                         ofs << " [ " << preamble << " ]";
1274                 }
1275                 ofs << ">\n\n";
1276
1277                 if (params().options.empty())
1278                         sgml::openTag(ofs, 0, false, top_element);
1279                 else {
1280                         string top = top_element;
1281                         top += ' ';
1282                         top += params().options;
1283                         sgml::openTag(ofs, 0, false, top);
1284                 }
1285         }
1286
1287         ofs << "<!-- LyX "  << lyx_version
1288             << " created this file. For more info see http://www.lyx.org/"
1289             << " -->\n";
1290
1291         Paragraph::depth_type depth = 0; // paragraph depth
1292         string item_name;
1293         vector<string> environment_stack(5);
1294
1295         ParagraphList::iterator pit = paragraphs().begin();
1296         ParagraphList::iterator pend = paragraphs().end();
1297         for (; pit != pend; ++pit) {
1298                 LyXLayout_ptr const & style = pit->layout();
1299                 // treat <toc> as a special case for compatibility with old code
1300                 if (pit->isInset(0)) {
1301                         InsetOld * inset = pit->getInset(0);
1302                         InsetOld::Code lyx_code = inset->lyxCode();
1303                         if (lyx_code == InsetOld::TOC_CODE) {
1304                                 string const temp = "toc";
1305                                 sgml::openTag(ofs, depth, false, temp);
1306                                 continue;
1307                         }
1308                 }
1309
1310                 // environment tag closing
1311                 for (; depth > pit->params().depth(); --depth) {
1312                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1313                         environment_stack[depth].erase();
1314                 }
1315
1316                 // write opening SGML tags
1317                 switch (style->latextype) {
1318                 case LATEX_PARAGRAPH:
1319                         if (depth == pit->params().depth()
1320                            && !environment_stack[depth].empty()) {
1321                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1322                                 environment_stack[depth].erase();
1323                                 if (depth)
1324                                         --depth;
1325                                 else
1326                                         ofs << "</p>";
1327                         }
1328                         sgml::openTag(ofs, depth, false, style->latexname());
1329                         break;
1330
1331                 case LATEX_COMMAND:
1332                         if (depth != 0)
1333                                 error(ErrorItem(_("Error:"), _("Wrong depth for LatexType Command.\n"), pit->id(), 0, pit->size()));
1334
1335                         if (!environment_stack[depth].empty()) {
1336                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1337                                 ofs << "</p>";
1338                         }
1339
1340                         environment_stack[depth].erase();
1341                         sgml::openTag(ofs, depth, false, style->latexname());
1342                         break;
1343
1344                 case LATEX_ENVIRONMENT:
1345                 case LATEX_ITEM_ENVIRONMENT:
1346                 case LATEX_BIB_ENVIRONMENT:
1347                 {
1348                         string const & latexname = style->latexname();
1349
1350                         if (depth == pit->params().depth()
1351                             && environment_stack[depth] != latexname) {
1352                                 sgml::closeTag(ofs, depth, false,
1353                                              environment_stack[depth]);
1354                                 environment_stack[depth].erase();
1355                         }
1356                         if (depth < pit->params().depth()) {
1357                                depth = pit->params().depth();
1358                                environment_stack[depth].erase();
1359                         }
1360                         if (environment_stack[depth] != latexname) {
1361                                 if (depth == 0) {
1362                                         sgml::openTag(ofs, depth, false, "p");
1363                                 }
1364                                 sgml::openTag(ofs, depth, false, latexname);
1365
1366                                 if (environment_stack.size() == depth + 1)
1367                                         environment_stack.push_back("!-- --");
1368                                 environment_stack[depth] = latexname;
1369                         }
1370
1371                         if (style->latexparam() == "CDATA")
1372                                 ofs << "<![CDATA[";
1373
1374                         if (style->latextype == LATEX_ENVIRONMENT) break;
1375
1376                         if (style->labeltype == LABEL_MANUAL)
1377                                 item_name = "tag";
1378                         else
1379                                 item_name = "item";
1380
1381                         sgml::openTag(ofs, depth + 1, false, item_name);
1382                 }
1383                 break;
1384
1385                 default:
1386                         sgml::openTag(ofs, depth, false, style->latexname());
1387                         break;
1388                 }
1389
1390                 simpleLinuxDocOnePar(ofs, pit, depth);
1391
1392                 ofs << "\n";
1393                 // write closing SGML tags
1394                 switch (style->latextype) {
1395                 case LATEX_COMMAND:
1396                         break;
1397                 case LATEX_ENVIRONMENT:
1398                 case LATEX_ITEM_ENVIRONMENT:
1399                 case LATEX_BIB_ENVIRONMENT:
1400                         if (style->latexparam() == "CDATA")
1401                                 ofs << "]]>";
1402                         break;
1403                 default:
1404                         sgml::closeTag(ofs, depth, false, style->latexname());
1405                         break;
1406                 }
1407         }
1408
1409         // Close open tags
1410         for (int i = depth; i >= 0; --i)
1411                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1412
1413         if (!body_only) {
1414                 ofs << "\n\n";
1415                 sgml::closeTag(ofs, 0, false, top_element);
1416         }
1417
1418         ofs.close();
1419         // How to check for successful close
1420
1421         // we want this to be true outside previews (for insetexternal)
1422         niceFile() = true;
1423 }
1424
1425
1426 // checks, if newcol chars should be put into this line
1427 // writes newline, if necessary.
1428 namespace {
1429
1430 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1431                           string::size_type newcol)
1432 {
1433         colcount += newcol;
1434         if (colcount > lyxrc.ascii_linelen) {
1435                 os << "\n";
1436                 colcount = newcol; // assume write after this call
1437         }
1438 }
1439
1440 enum PAR_TAG {
1441         NONE=0,
1442         TT = 1,
1443         SF = 2,
1444         BF = 4,
1445         IT = 8,
1446         SL = 16,
1447         EM = 32
1448 };
1449
1450
1451 string tag_name(PAR_TAG const & pt) {
1452         switch (pt) {
1453         case NONE: return "!-- --";
1454         case TT: return "tt";
1455         case SF: return "sf";
1456         case BF: return "bf";
1457         case IT: return "it";
1458         case SL: return "sl";
1459         case EM: return "em";
1460         }
1461         return "";
1462 }
1463
1464
1465 inline
1466 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1467 {
1468         p1 = static_cast<PAR_TAG>(p1 | p2);
1469 }
1470
1471
1472 inline
1473 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1474 {
1475         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1476 }
1477
1478 } // anon
1479
1480
1481 // Handle internal paragraph parsing -- layout already processed.
1482 void Buffer::simpleLinuxDocOnePar(ostream & os,
1483         ParagraphList::iterator par,
1484         Paragraph::depth_type /*depth*/) const
1485 {
1486         LyXLayout_ptr const & style = par->layout();
1487
1488         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1489
1490         // gets paragraph main font
1491         LyXFont font_old;
1492         bool desc_on;
1493         if (style->labeltype == LABEL_MANUAL) {
1494                 font_old = style->labelfont;
1495                 desc_on = true;
1496         } else {
1497                 font_old = style->font;
1498                 desc_on = false;
1499         }
1500
1501         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1502         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1503         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1504         bool is_em = false;
1505
1506         stack<PAR_TAG> tag_state;
1507         // parsing main loop
1508         for (pos_type i = 0; i < par->size(); ++i) {
1509
1510                 PAR_TAG tag_close = NONE;
1511                 list < PAR_TAG > tag_open;
1512
1513                 LyXFont const font = par->getFont(params(), i, outerFont(par, paragraphs()));
1514
1515                 if (font_old.family() != font.family()) {
1516                         switch (family_type) {
1517                         case LyXFont::SANS_FAMILY:
1518                                 tag_close |= SF;
1519                                 break;
1520                         case LyXFont::TYPEWRITER_FAMILY:
1521                                 tag_close |= TT;
1522                                 break;
1523                         default:
1524                                 break;
1525                         }
1526
1527                         family_type = font.family();
1528
1529                         switch (family_type) {
1530                         case LyXFont::SANS_FAMILY:
1531                                 tag_open.push_back(SF);
1532                                 break;
1533                         case LyXFont::TYPEWRITER_FAMILY:
1534                                 tag_open.push_back(TT);
1535                                 break;
1536                         default:
1537                                 break;
1538                         }
1539                 }
1540
1541                 if (font_old.series() != font.series()) {
1542                         switch (series_type) {
1543                         case LyXFont::BOLD_SERIES:
1544                                 tag_close |= BF;
1545                                 break;
1546                         default:
1547                                 break;
1548                         }
1549
1550                         series_type = font.series();
1551
1552                         switch (series_type) {
1553                         case LyXFont::BOLD_SERIES:
1554                                 tag_open.push_back(BF);
1555                                 break;
1556                         default:
1557                                 break;
1558                         }
1559
1560                 }
1561
1562                 if (font_old.shape() != font.shape()) {
1563                         switch (shape_type) {
1564                         case LyXFont::ITALIC_SHAPE:
1565                                 tag_close |= IT;
1566                                 break;
1567                         case LyXFont::SLANTED_SHAPE:
1568                                 tag_close |= SL;
1569                                 break;
1570                         default:
1571                                 break;
1572                         }
1573
1574                         shape_type = font.shape();
1575
1576                         switch (shape_type) {
1577                         case LyXFont::ITALIC_SHAPE:
1578                                 tag_open.push_back(IT);
1579                                 break;
1580                         case LyXFont::SLANTED_SHAPE:
1581                                 tag_open.push_back(SL);
1582                                 break;
1583                         default:
1584                                 break;
1585                         }
1586                 }
1587                 // handle <em> tag
1588                 if (font_old.emph() != font.emph()) {
1589                         if (font.emph() == LyXFont::ON) {
1590                                 tag_open.push_back(EM);
1591                                 is_em = true;
1592                         }
1593                         else if (is_em) {
1594                                 tag_close |= EM;
1595                                 is_em = false;
1596                         }
1597                 }
1598
1599                 list < PAR_TAG > temp;
1600                 while (!tag_state.empty() && tag_close) {
1601                         PAR_TAG k =  tag_state.top();
1602                         tag_state.pop();
1603                         os << "</" << tag_name(k) << '>';
1604                         if (tag_close & k)
1605                                 reset(tag_close,k);
1606                         else
1607                                 temp.push_back(k);
1608                 }
1609
1610                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1611                     j != temp.end(); ++j) {
1612                         tag_state.push(*j);
1613                         os << '<' << tag_name(*j) << '>';
1614                 }
1615
1616                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1617                     j != tag_open.end(); ++j) {
1618                         tag_state.push(*j);
1619                         os << '<' << tag_name(*j) << '>';
1620                 }
1621
1622                 char c = par->getChar(i);
1623
1624                 if (c == Paragraph::META_INSET) {
1625                         InsetOld * inset = par->getInset(i);
1626                         inset->linuxdoc(*this, os);
1627                         font_old = font;
1628                         continue;
1629                 }
1630
1631                 if (style->latexparam() == "CDATA") {
1632                         // "TeX"-Mode on == > SGML-Mode on.
1633                         if (c != '\0')
1634                                 os << c;
1635                         ++char_line_count;
1636                 } else {
1637                         bool ws;
1638                         string str;
1639                         boost::tie(ws, str) = sgml::escapeChar(c);
1640                         if (ws && !par->isFreeSpacing()) {
1641                                 // in freespacing mode, spaces are
1642                                 // non-breaking characters
1643                                 if (desc_on) {// if char is ' ' then...
1644
1645                                         ++char_line_count;
1646                                         sgmlLineBreak(os, char_line_count, 6);
1647                                         os << "</tag>";
1648                                         desc_on = false;
1649                                 } else  {
1650                                         sgmlLineBreak(os, char_line_count, 1);
1651                                         os << c;
1652                                 }
1653                         } else {
1654                                 os << str;
1655                                 char_line_count += str.length();
1656                         }
1657                 }
1658                 font_old = font;
1659         }
1660
1661         while (!tag_state.empty()) {
1662                 os << "</" << tag_name(tag_state.top()) << '>';
1663                 tag_state.pop();
1664         }
1665
1666         // resets description flag correctly
1667         if (desc_on) {
1668                 // <tag> not closed...
1669                 sgmlLineBreak(os, char_line_count, 6);
1670                 os << "</tag>";
1671         }
1672 }
1673
1674
1675 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1676 {
1677         ofstream ofs;
1678         if (!::openFileWrite(ofs, fname))
1679                 return;
1680
1681         niceFile() = nice; // this will be used by Insetincludes.
1682
1683         LaTeXFeatures features(*this, params());
1684         validate(features);
1685
1686         texrow().reset();
1687
1688         LyXTextClass const & tclass = params().getLyXTextClass();
1689         string top_element = tclass.latexname();
1690
1691         if (!only_body) {
1692                 ofs << "<!DOCTYPE " << top_element
1693                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1694
1695                 string preamble = params().preamble;
1696                 string const name = nice ? ChangeExtension(pimpl_->filename, ".sgml")
1697                          : fname;
1698                 preamble += features.getIncludedFiles(name);
1699                 preamble += features.getLyXSGMLEntities();
1700
1701                 if (!preamble.empty()) {
1702                         ofs << "\n [ " << preamble << " ]";
1703                 }
1704                 ofs << ">\n\n";
1705         }
1706
1707         string top = top_element;
1708         top += " lang=\"";
1709         top += params().language->code();
1710         top += '"';
1711
1712         if (!params().options.empty()) {
1713                 top += ' ';
1714                 top += params().options;
1715         }
1716         sgml::openTag(ofs, 0, false, top);
1717
1718         ofs << "<!-- DocBook file was created by LyX " << lyx_version
1719             << "\n  See http://www.lyx.org/ for more information -->\n";
1720
1721         vector<string> environment_stack(10);
1722         vector<string> environment_inner(10);
1723         vector<string> command_stack(10);
1724
1725         bool command_flag = false;
1726         Paragraph::depth_type command_depth = 0;
1727         Paragraph::depth_type command_base = 0;
1728         Paragraph::depth_type cmd_depth = 0;
1729         Paragraph::depth_type depth = 0; // paragraph depth
1730
1731         string item_name;
1732         string command_name;
1733
1734         ParagraphList::iterator par = paragraphs().begin();
1735         ParagraphList::iterator pend = paragraphs().end();
1736
1737         for (; par != pend; ++par) {
1738                 string sgmlparam;
1739                 string c_depth;
1740                 string c_params;
1741                 int desc_on = 0; // description mode
1742
1743                 LyXLayout_ptr const & style = par->layout();
1744
1745                 // environment tag closing
1746                 for (; depth > par->params().depth(); --depth) {
1747                         if (environment_inner[depth] != "!-- --" && !environment_inner[depth].empty()) {
1748                                 item_name = "listitem";
1749                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1750                                 if (environment_inner[depth] == "varlistentry")
1751                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
1752                         }
1753                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1754                         environment_stack[depth].erase();
1755                         environment_inner[depth].erase();
1756                 }
1757
1758                 if (depth == par->params().depth()
1759                    && environment_stack[depth] != style->latexname()
1760                    && !environment_stack[depth].empty()) {
1761                         if (environment_inner[depth] != "!-- --") {
1762                                 item_name= "listitem";
1763                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
1764                                 if (environment_inner[depth] == "varlistentry")
1765                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1766                         }
1767
1768                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1769
1770                         environment_stack[depth].erase();
1771                         environment_inner[depth].erase();
1772                 }
1773
1774                 // Write opening SGML tags.
1775                 switch (style->latextype) {
1776                 case LATEX_PARAGRAPH:
1777                         sgml::openTag(ofs, depth + command_depth,
1778                                     false, style->latexname());
1779                         break;
1780
1781                 case LATEX_COMMAND:
1782                         if (depth != 0)
1783                                 error(ErrorItem(_("Error"), _("Wrong depth for LatexType Command."), par->id(), 0, par->size()));
1784
1785                         command_name = style->latexname();
1786
1787                         sgmlparam = style->latexparam();
1788                         c_params = split(sgmlparam, c_depth,'|');
1789
1790                         cmd_depth = atoi(c_depth);
1791
1792                         if (command_flag) {
1793                                 if (cmd_depth < command_base) {
1794                                         for (Paragraph::depth_type j = command_depth;
1795                                              j >= command_base; --j) {
1796                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1797                                                 ofs << endl;
1798                                         }
1799                                         command_depth = command_base = cmd_depth;
1800                                 } else if (cmd_depth <= command_depth) {
1801                                         for (int j = command_depth;
1802                                              j >= int(cmd_depth); --j) {
1803                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1804                                                 ofs << endl;
1805                                         }
1806                                         command_depth = cmd_depth;
1807                                 } else
1808                                         command_depth = cmd_depth;
1809                         } else {
1810                                 command_depth = command_base = cmd_depth;
1811                                 command_flag = true;
1812                         }
1813                         if (command_stack.size() == command_depth + 1)
1814                                 command_stack.push_back(string());
1815                         command_stack[command_depth] = command_name;
1816
1817                         // treat label as a special case for
1818                         // more WYSIWYM handling.
1819                         // This is a hack while paragraphs can't have
1820                         // attributes, like id in this case.
1821                         if (par->isInset(0)) {
1822                                 InsetOld * inset = par->getInset(0);
1823                                 InsetOld::Code lyx_code = inset->lyxCode();
1824                                 if (lyx_code == InsetOld::LABEL_CODE) {
1825                                         command_name += " id=\"";
1826                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
1827                                         command_name += '"';
1828                                         desc_on = 3;
1829                                 }
1830                         }
1831
1832                         sgml::openTag(ofs, depth + command_depth, false, command_name);
1833
1834                         item_name = c_params.empty() ? "title" : c_params;
1835                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
1836                         break;
1837
1838                 case LATEX_ENVIRONMENT:
1839                 case LATEX_ITEM_ENVIRONMENT:
1840                         if (depth < par->params().depth()) {
1841                                 depth = par->params().depth();
1842                                 environment_stack[depth].erase();
1843                         }
1844
1845                         if (environment_stack[depth] != style->latexname()) {
1846                                 if (environment_stack.size() == depth + 1) {
1847                                         environment_stack.push_back("!-- --");
1848                                         environment_inner.push_back("!-- --");
1849                                 }
1850                                 environment_stack[depth] = style->latexname();
1851                                 environment_inner[depth] = "!-- --";
1852                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
1853                         } else {
1854                                 if (environment_inner[depth] != "!-- --") {
1855                                         item_name= "listitem";
1856                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
1857                                         if (environment_inner[depth] == "varlistentry")
1858                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1859                                 }
1860                         }
1861
1862                         if (style->latextype == LATEX_ENVIRONMENT) {
1863                                 if (!style->latexparam().empty()) {
1864                                         if (style->latexparam() == "CDATA")
1865                                                 ofs << "<![CDATA[";
1866                                         else
1867                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
1868                                 }
1869                                 break;
1870                         }
1871
1872                         desc_on = (style->labeltype == LABEL_MANUAL);
1873
1874                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1875                         sgml::openTag(ofs, depth + 1 + command_depth,
1876                                     false, environment_inner[depth]);
1877
1878                         item_name = desc_on ? "term" : "para";
1879                         sgml::openTag(ofs, depth + 1 + command_depth,
1880                                     false, item_name);
1881                         break;
1882                 default:
1883                         sgml::openTag(ofs, depth + command_depth,
1884                                     false, style->latexname());
1885                         break;
1886                 }
1887
1888                 simpleDocBookOnePar(ofs, par, desc_on,
1889                                     depth + 1 + command_depth);
1890
1891                 string end_tag;
1892                 // write closing SGML tags
1893                 switch (style->latextype) {
1894                 case LATEX_COMMAND:
1895                         end_tag = c_params.empty() ? "title" : c_params;
1896                         sgml::closeTag(ofs, depth + command_depth,
1897                                      false, end_tag);
1898                         break;
1899                 case LATEX_ENVIRONMENT:
1900                         if (!style->latexparam().empty()) {
1901                                 if (style->latexparam() == "CDATA")
1902                                         ofs << "]]>";
1903                                 else
1904                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
1905                         }
1906                         break;
1907                 case LATEX_ITEM_ENVIRONMENT:
1908                         if (desc_on == 1) break;
1909                         end_tag = "para";
1910                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
1911                         break;
1912                 case LATEX_PARAGRAPH:
1913                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1914                         break;
1915                 default:
1916                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1917                         break;
1918                 }
1919         }
1920
1921         // Close open tags
1922         for (int d = depth; d >= 0; --d) {
1923                 if (!environment_stack[depth].empty()) {
1924                         if (environment_inner[depth] != "!-- --") {
1925                                 item_name = "listitem";
1926                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1927                                if (environment_inner[depth] == "varlistentry")
1928                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1929                         }
1930
1931                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1932                 }
1933         }
1934
1935         for (int j = command_depth; j >= 0 ; --j)
1936                 if (!command_stack[j].empty()) {
1937                         sgml::closeTag(ofs, j, false, command_stack[j]);
1938                         ofs << endl;
1939                 }
1940
1941         ofs << "\n\n";
1942         sgml::closeTag(ofs, 0, false, top_element);
1943
1944         ofs.close();
1945         // How to check for successful close
1946
1947         // we want this to be true outside previews (for insetexternal)
1948         niceFile() = true;
1949 }
1950
1951
1952 void Buffer::simpleDocBookOnePar(ostream & os,
1953                                  ParagraphList::iterator par, int & desc_on,
1954                                  Paragraph::depth_type depth) const
1955 {
1956         bool emph_flag = false;
1957
1958         LyXLayout_ptr const & style = par->layout();
1959
1960         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
1961
1962         int char_line_count = depth;
1963         //if (!style.free_spacing)
1964         //      os << string(depth,' ');
1965
1966         // parsing main loop
1967         for (pos_type i = 0; i < par->size(); ++i) {
1968                 LyXFont font = par->getFont(params(), i, outerFont(par, paragraphs()));
1969
1970                 // handle <emphasis> tag
1971                 if (font_old.emph() != font.emph()) {
1972                         if (font.emph() == LyXFont::ON) {
1973                                 if (style->latexparam() == "CDATA")
1974                                         os << "]]>";
1975                                 os << "<emphasis>";
1976                                 if (style->latexparam() == "CDATA")
1977                                         os << "<![CDATA[";
1978                                 emph_flag = true;
1979                         } else if (i) {
1980                                 if (style->latexparam() == "CDATA")
1981                                         os << "]]>";
1982                                 os << "</emphasis>";
1983                                 if (style->latexparam() == "CDATA")
1984                                         os << "<![CDATA[";
1985                                 emph_flag = false;
1986                         }
1987                 }
1988
1989
1990                 if (par->isInset(i)) {
1991                         InsetOld * inset = par->getInset(i);
1992                         // don't print the inset in position 0 if desc_on == 3 (label)
1993                         if (i || desc_on != 3) {
1994                                 if (style->latexparam() == "CDATA")
1995                                         os << "]]>";
1996                                 inset->docbook(*this, os, false);
1997                                 if (style->latexparam() == "CDATA")
1998                                         os << "<![CDATA[";
1999                         }
2000                 } else {
2001                         char c = par->getChar(i);
2002                         bool ws;
2003                         string str;
2004                         boost::tie(ws, str) = sgml::escapeChar(c);
2005
2006                         if (style->pass_thru) {
2007                                 os << c;
2008                         } else if (par->isFreeSpacing() || c != ' ') {
2009                                         os << str;
2010                         } else if (desc_on == 1) {
2011                                 ++char_line_count;
2012                                 os << "\n</term><listitem><para>";
2013                                 desc_on = 2;
2014                         } else {
2015                                 os << ' ';
2016                         }
2017                 }
2018                 font_old = font;
2019         }
2020
2021         if (emph_flag) {
2022                 if (style->latexparam() == "CDATA")
2023                         os << "]]>";
2024                 os << "</emphasis>";
2025                 if (style->latexparam() == "CDATA")
2026                         os << "<![CDATA[";
2027         }
2028
2029         // resets description flag correctly
2030         if (desc_on == 1) {
2031                 // <term> not closed...
2032                 os << "</term>\n<listitem><para>&nbsp;</para>";
2033         }
2034         if (style->free_spacing)
2035                 os << '\n';
2036 }
2037
2038
2039 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2040 // Other flags: -wall -v0 -x
2041 int Buffer::runChktex()
2042 {
2043         busy(true);
2044
2045         // get LaTeX-Filename
2046         string const name = getLatexName();
2047         string path = filePath();
2048
2049         string const org_path = path;
2050         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2051                 path = temppath();
2052         }
2053
2054         Path p(path); // path to LaTeX file
2055         message(_("Running chktex..."));
2056
2057         // Generate the LaTeX file if neccessary
2058         LatexRunParams runparams;
2059         runparams.flavor = LatexRunParams::LATEX;
2060         runparams.nice = false;
2061         makeLaTeXFile(name, org_path, runparams);
2062
2063         TeXErrors terr;
2064         Chktex chktex(lyxrc.chktex_command, name, filePath());
2065         int res = chktex.run(terr); // run chktex
2066
2067         if (res == -1) {
2068                 Alert::error(_("chktex failure"),
2069                              _("Could not run chktex successfully."));
2070         } else if (res > 0) {
2071                 // Insert all errors as errors boxes
2072                 bufferErrors(*this, terr);
2073         }
2074
2075         busy(false);
2076
2077         return res;
2078 }
2079
2080
2081 void Buffer::validate(LaTeXFeatures & features) const
2082 {
2083         LyXTextClass const & tclass = params().getLyXTextClass();
2084
2085         if (params().tracking_changes) {
2086                 features.require("dvipost");
2087                 features.require("color");
2088         }
2089
2090         // AMS Style is at document level
2091         if (params().use_amsmath == BufferParams::AMS_ON
2092             || tclass.provides(LyXTextClass::amsmath))
2093                 features.require("amsmath");
2094
2095         for_each(paragraphs().begin(), paragraphs().end(),
2096                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2097
2098         // the bullet shapes are buffer level not paragraph level
2099         // so they are tested here
2100         for (int i = 0; i < 4; ++i) {
2101                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
2102                         int const font = params().user_defined_bullet(i).getFont();
2103                         if (font == 0) {
2104                                 int const c = params()
2105                                         .user_defined_bullet(i)
2106                                         .getCharacter();
2107                                 if (c == 16
2108                                    || c == 17
2109                                    || c == 25
2110                                    || c == 26
2111                                    || c == 31) {
2112                                         features.require("latexsym");
2113                                 }
2114                         } else if (font == 1) {
2115                                 features.require("amssymb");
2116                         } else if ((font >= 2 && font <= 5)) {
2117                                 features.require("pifont");
2118                         }
2119                 }
2120         }
2121
2122         if (lyxerr.debugging(Debug::LATEX)) {
2123                 features.showStruct();
2124         }
2125 }
2126
2127
2128 void Buffer::getLabelList(std::vector<string> & list) const
2129 {
2130         /// if this is a child document and the parent is already loaded
2131         /// Use the parent's list instead  [ale990407]
2132         if (!params().parentname.empty()
2133             && bufferlist.exists(params().parentname)) {
2134                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
2135                 if (tmp) {
2136                         tmp->getLabelList(list);
2137                         return;
2138                 }
2139         }
2140
2141         for (inset_iterator it = inset_const_iterator_begin();
2142              it != inset_const_iterator_end(); ++it) {
2143                 it->getLabelList(*this, list);
2144         }
2145 }
2146
2147
2148 // This is also a buffer property (ale)
2149 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys) const
2150 {
2151         /// if this is a child document and the parent is already loaded
2152         /// use the parent's list instead  [ale990412]
2153         if (!params().parentname.empty() &&
2154             bufferlist.exists(params().parentname)) {
2155                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
2156                 if (tmp) {
2157                         tmp->fillWithBibKeys(keys);
2158                         return;
2159                 }
2160         }
2161
2162         for (inset_iterator it = inset_const_iterator_begin();
2163                 it != inset_const_iterator_end(); ++it) {
2164                 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
2165                         InsetBibtex const & inset =
2166                                 dynamic_cast<InsetBibtex const &>(*it);
2167                         inset.fillWithBibKeys(*this, keys);
2168                 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
2169                         InsetInclude const & inset =
2170                                 dynamic_cast<InsetInclude const &>(*it);
2171                         inset.fillWithBibKeys(*this, keys);
2172                 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
2173                         InsetBibitem const & inset =
2174                                 dynamic_cast<InsetBibitem const &>(*it);
2175                         string const key = inset.getContents();
2176                         string const opt = inset.getOptions();
2177                         string const ref; // = pit->asString(this, false);
2178                         string const info = opt + "TheBibliographyRef" + ref;
2179                         keys.push_back(pair<string, string>(key, info));
2180                 }
2181         }
2182 }
2183
2184
2185 bool Buffer::isDepClean(string const & name) const
2186 {
2187         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
2188         if (it == pimpl_->dep_clean.end())
2189                 return true;
2190         return it->second;
2191 }
2192
2193
2194 void Buffer::markDepClean(string const & name)
2195 {
2196         pimpl_->dep_clean[name] = true;
2197 }
2198
2199
2200 bool Buffer::dispatch(string const & command, bool * result)
2201 {
2202         // Split command string into command and argument
2203         string cmd;
2204         string line = ltrim(command);
2205         string const arg = trim(split(line, cmd, ' '));
2206
2207         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2208 }
2209
2210
2211 bool Buffer::dispatch(int action, string const & argument, bool * result)
2212 {
2213         bool dispatched = true;
2214
2215         switch (action) {
2216                 case LFUN_EXPORT: {
2217                         bool const tmp = Exporter::Export(this, argument, false);
2218                         if (result)
2219                                 *result = tmp;
2220                         break;
2221                 }
2222
2223                 default:
2224                         dispatched = false;
2225         }
2226         return dispatched;
2227 }
2228
2229
2230 void Buffer::changeLanguage(Language const * from, Language const * to)
2231 {
2232         lyxerr << "Changing Language!" << endl;
2233
2234         // Take care of l10n/i18n
2235         updateDocLang(to);
2236
2237         ParIterator end = par_iterator_end();
2238         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2239                 it->changeLanguage(params(), from, to);
2240 }
2241
2242
2243 void Buffer::updateDocLang(Language const * nlang)
2244 {
2245         pimpl_->messages.reset(new Messages(nlang->code()));
2246 }
2247
2248
2249 bool Buffer::isMultiLingual()
2250 {
2251         ParIterator end = par_iterator_end();
2252         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2253                 if (it->isMultiLingual(params()))
2254                         return true;
2255
2256         return false;
2257 }
2258
2259
2260 void Buffer::inset_iterator::setParagraph()
2261 {
2262         while (pit != pend) {
2263                 it = pit->insetlist.begin();
2264                 if (it != pit->insetlist.end())
2265                         return;
2266                 ++pit;
2267         }
2268 }
2269
2270
2271 InsetOld * Buffer::getInsetFromID(int id_arg) const
2272 {
2273         for (inset_iterator it = inset_const_iterator_begin();
2274                  it != inset_const_iterator_end(); ++it)
2275         {
2276                 if (it->id() == id_arg)
2277                         return &(*it);
2278                 InsetOld * in = it->getInsetFromID(id_arg);
2279                 if (in)
2280                         return in;
2281         }
2282         return 0;
2283 }
2284
2285
2286 ParIterator Buffer::getParFromID(int id) const
2287 {
2288 #warning FIXME: const correctness! (Andre)
2289         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
2290         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
2291
2292 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
2293         if (id < 0) {
2294                 // John says this is called with id == -1 from undo
2295                 lyxerr << "getParFromID(), id: " << id << endl;
2296                 return end;
2297         }
2298
2299         for (; it != end; ++it)
2300                 if (it->id() == id)
2301                         return it;
2302
2303         return end;
2304 }
2305
2306
2307 bool Buffer::hasParWithID(int id) const
2308 {
2309         ParConstIterator it = par_iterator_begin();
2310         ParConstIterator end = par_iterator_end();
2311
2312         if (id < 0) {
2313                 // John says this is called with id == -1 from undo
2314                 lyxerr << "hasParWithID(), id: " << id << endl;
2315                 return 0;
2316         }
2317
2318         for (; it != end; ++it)
2319                 if (it->id() == id)
2320                         return true;
2321
2322         return false;
2323 }
2324
2325
2326 ParIterator Buffer::par_iterator_begin()
2327 {
2328         return ParIterator(paragraphs().begin(), paragraphs());
2329 }
2330
2331
2332 ParIterator Buffer::par_iterator_end()
2333 {
2334         return ParIterator(paragraphs().end(), paragraphs());
2335 }
2336
2337
2338 ParConstIterator Buffer::par_iterator_begin() const
2339 {
2340         ParagraphList const & pars = paragraphs();
2341         return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
2342 }
2343
2344
2345 ParConstIterator Buffer::par_iterator_end() const
2346 {
2347         ParagraphList const & pars = paragraphs();
2348         return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
2349 }
2350
2351
2352 Language const * Buffer::getLanguage() const
2353 {
2354         return params().language;
2355 }
2356
2357
2358 string const Buffer::B_(string const & l10n) const
2359 {
2360         if (pimpl_->messages.get()) {
2361                 return pimpl_->messages->get(l10n);
2362         }
2363
2364         return _(l10n);
2365 }
2366
2367
2368 bool Buffer::isClean() const
2369 {
2370         return pimpl_->lyx_clean;
2371 }
2372
2373
2374 bool Buffer::isBakClean() const
2375 {
2376         return pimpl_->bak_clean;
2377 }
2378
2379
2380 void Buffer::markClean() const
2381 {
2382         if (!pimpl_->lyx_clean) {
2383                 pimpl_->lyx_clean = true;
2384                 updateTitles();
2385         }
2386         // if the .lyx file has been saved, we don't need an
2387         // autosave
2388         pimpl_->bak_clean = true;
2389 }
2390
2391
2392 void Buffer::markBakClean()
2393 {
2394         pimpl_->bak_clean = true;
2395 }
2396
2397
2398 void Buffer::setUnnamed(bool flag)
2399 {
2400         pimpl_->unnamed = flag;
2401 }
2402
2403
2404 bool Buffer::isUnnamed()
2405 {
2406         return pimpl_->unnamed;
2407 }
2408
2409
2410 void Buffer::markDirty()
2411 {
2412         if (pimpl_->lyx_clean) {
2413                 pimpl_->lyx_clean = false;
2414                 updateTitles();
2415         }
2416         pimpl_->bak_clean = false;
2417
2418         DepClean::iterator it = pimpl_->dep_clean.begin();
2419         DepClean::const_iterator const end = pimpl_->dep_clean.end();
2420
2421         for (; it != end; ++it) {
2422                 it->second = false;
2423         }
2424 }
2425
2426
2427 string const & Buffer::fileName() const
2428 {
2429         return pimpl_->filename;
2430 }
2431
2432
2433 string const & Buffer::filePath() const
2434 {
2435         return pimpl_->filepath;
2436 }
2437
2438
2439 bool Buffer::isReadonly() const
2440 {
2441         return pimpl_->read_only;
2442 }
2443
2444
2445 void Buffer::setParentName(string const & name)
2446 {
2447         params().parentname = name;
2448 }
2449
2450
2451 Buffer::inset_iterator::inset_iterator()
2452         : pit(), pend()
2453 {}
2454
2455
2456 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2457         : pit(p), pend(e)
2458 {
2459         setParagraph();
2460 }
2461
2462
2463 Buffer::inset_iterator Buffer::inset_iterator_begin()
2464 {
2465         return inset_iterator(paragraphs().begin(), paragraphs().end());
2466 }
2467
2468
2469 Buffer::inset_iterator Buffer::inset_iterator_end()
2470 {
2471         return inset_iterator(paragraphs().end(), paragraphs().end());
2472 }
2473
2474
2475 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
2476 {
2477         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
2478         return inset_iterator(pars.begin(), pars.end());
2479 }
2480
2481
2482 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
2483 {
2484         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
2485         return inset_iterator(pars.end(), pars.end());
2486 }
2487
2488
2489 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2490 {
2491         if (pit != pend) {
2492                 ++it;
2493                 if (it == pit->insetlist.end()) {
2494                         ++pit;
2495                         setParagraph();
2496                 }
2497         }
2498         return *this;
2499 }
2500
2501
2502 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2503 {
2504         inset_iterator tmp = *this;
2505         ++*this;
2506         return tmp;
2507 }
2508
2509
2510 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2511 {
2512         return *it->inset;
2513 }
2514
2515
2516 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2517 {
2518         return it->inset;
2519 }
2520
2521
2522 ParagraphList::iterator Buffer::inset_iterator::getPar() const
2523 {
2524         return pit;
2525 }
2526
2527
2528 lyx::pos_type Buffer::inset_iterator::getPos() const
2529 {
2530         return it->pos;
2531 }
2532
2533
2534 bool operator==(Buffer::inset_iterator const & iter1,
2535                 Buffer::inset_iterator const & iter2)
2536 {
2537         return iter1.pit == iter2.pit
2538                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2539 }
2540
2541
2542 bool operator!=(Buffer::inset_iterator const & iter1,
2543                 Buffer::inset_iterator const & iter2)
2544 {
2545         return !(iter1 == iter2);
2546 }