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