]> git.lyx.org Git - features.git/blob - src/Buffer.h
d713c8ac0f037db54903b0c501e7f933380f47db
[features.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "insets/InsetCode.h"
16
17 #include "support/FileName.h"
18 #include "support/docstring.h"
19 #include "support/docstream.h"
20 #include "support/types.h"
21
22 #include <iosfwd>
23 #include <string>
24 #include <utility>
25 #include <vector>
26
27
28 namespace lyx {
29
30 class BufferParams;
31 class EmbeddedFiles;
32 class ErrorItem;
33 class ErrorList;
34 class FuncRequest;
35 class Inset;
36 class Font;
37 class Format;
38 class Lexer;
39 class LyXRC;
40 class Text;
41 class LyXVC;
42 class LaTeXFeatures;
43 class Language;
44 class MacroData;
45 class OutputParams;
46 class Paragraph;
47 class ParConstIterator;
48 class ParIterator;
49 class ParagraphList;
50 class TeXErrors;
51 class TexRow;
52 class TocBackend;
53 class Undo;
54
55 namespace frontend {
56 class GuiBufferDelegate;
57 class WorkAreaManager;
58 }
59
60 /** The buffer object.
61  * This is the buffer object. It contains all the informations about
62  * a document loaded into LyX.
63  * The buffer object owns the Text (wrapped in an InsetText), which
64  * contains the individual paragraphs of the document.
65  *
66  *
67  * I am not sure if the class is complete or
68  * minimal, probably not.
69  * \author Lars Gullik Bjønnes
70  */
71 class Buffer {
72 public:
73         /// What type of log will \c getLogName() return?
74         enum LogType {
75                 latexlog, ///< LaTeX log
76                 buildlog  ///< Literate build log
77         };
78
79         /// Result of \c readFile()
80         enum ReadStatus {
81                 failure, ///< The file could not be read
82                 success, ///< The file could not be read
83                 wrongversion ///< The version of the file does not match ours
84         };
85
86         /// Method to check if a file is externally modified, used by 
87         /// isExternallyModified()
88         /**
89          * timestamp is fast but inaccurate. For example, the granularity
90          * of timestamp on a FAT filesystem is 2 second. Also, various operations
91          * may touch the timestamp of a file even when its content is unchanged.
92          *
93          * checksum is accurate but slow, which can be a problem when it is 
94          * frequently used, or used for a large file on a slow (network) file
95          * system.
96          */
97         enum CheckMethod {
98                 checksum_method,  ///< Use file check sum
99                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
100         };
101         
102         /** Constructor
103             \param file
104             \param b  optional \c false by default
105         */
106         explicit Buffer(std::string const & file, bool b = false);
107
108         /// Destructor
109         ~Buffer();
110
111         /** High-level interface to buffer functionality.
112             This function parses a command string and executes it
113         */
114         bool dispatch(std::string const & command, bool * result = 0);
115
116         /// Maybe we know the function already by number...
117         bool dispatch(FuncRequest const & func, bool * result = 0);
118
119         /// Load the autosaved file.
120         void loadAutoSaveFile();
121
122         /// read a new document from a string
123         bool readString(std::string const &);
124         /// load a new file
125         bool readFile(support::FileName const & filename);
126
127         /// read the header, returns number of unknown tokens
128         int readHeader(Lexer & lex);
129
130         /** Reads a file without header.
131             \param par if != 0 insert the file.
132             \return \c false if file is not completely read.
133         */
134         bool readDocument(Lexer &);
135
136         ///
137         void insertStringAsLines(ParagraphList & plist,
138                 pit_type &, pos_type &,
139                 Font const &, docstring const &, bool);
140         ///
141         ParIterator getParFromID(int id) const;
142         /// do we have a paragraph with this id?
143         bool hasParWithID(int id) const;
144
145         ///
146         frontend::WorkAreaManager & workAreaManager() const;
147
148         /** Save file.
149             Takes care of auto-save files and backup file if requested.
150             Returns \c true if the save is successful, \c false otherwise.
151         */
152         bool save() const;
153
154         /// Write document to stream. Returns \c false if unsuccesful.
155         bool write(std::ostream &) const;
156         /// Write file. Returns \c false if unsuccesful.
157         bool writeFile(support::FileName const &) const;
158
159   /// Loads LyX file \c filename into buffer, *  and \return success 
160         bool loadLyXFile(support::FileName const & s);
161
162         /// Fill in the ErrorList with the TeXErrors
163         void bufferErrors(TeXErrors const &, ErrorList &) const;
164
165         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
166         bool makeLaTeXFile(support::FileName const & filename,
167                            std::string const & original_path,
168                            OutputParams const &,
169                            bool output_preamble = true,
170                            bool output_body = true);
171         /** Export the buffer to LaTeX.
172             If \p os is a file stream, and params().inputenc is "auto" or
173             "default", and the buffer contains text in different languages
174             with more than one encoding, then this method will change the
175             encoding associated to \p os. Therefore you must not call this
176             method with a string stream if the output is supposed to go to a
177             file. \code
178             odocfstream ofs;
179             ofs.open("test.tex");
180             writeLaTeXSource(ofs, ...);
181             ofs.close();
182             \endcode is NOT equivalent to \code
183             odocstringstream oss;
184             writeLaTeXSource(oss, ...);
185             odocfstream ofs;
186             ofs.open("test.tex");
187             ofs << oss.str();
188             ofs.close();
189             \endcode
190          */
191         void writeLaTeXSource(odocstream & os,
192                            std::string const & original_path,
193                            OutputParams const &,
194                            bool output_preamble = true,
195                            bool output_body = true);
196         ///
197         void makeDocBookFile(support::FileName const & filename,
198                              OutputParams const & runparams_in,
199                              bool only_body = false);
200         ///
201         void writeDocBookSource(odocstream & os, std::string const & filename,
202                              OutputParams const & runparams_in,
203                              bool only_body = false);
204         /// returns the main language for the buffer (document)
205         Language const * language() const;
206         /// get l10n translated to the buffers language
207         docstring const B_(std::string const & l10n) const;
208
209         ///
210         int runChktex();
211         /// return true if the main lyx file does not need saving
212         bool isClean() const;
213         ///
214         bool isBakClean() const;
215         ///
216         bool isDepClean(std::string const & name) const;
217
218         /// whether or not disk file has been externally modified
219         bool isExternallyModified(CheckMethod method) const;
220
221         /// save timestamp and checksum of the given file.
222         void saveCheckSum(support::FileName const & file) const;
223
224         /// mark the main lyx file as not needing saving
225         void markClean() const;
226
227         ///
228         void markBakClean() const;
229
230         ///
231         void markDepClean(std::string const & name);
232
233         ///
234         void setUnnamed(bool flag = true);
235
236         ///
237         bool isUnnamed() const;
238
239         /// Mark this buffer as dirty.
240         void markDirty();
241
242         /// Returns the buffer's filename. It is always an absolute path.
243         std::string absFileName() const;
244
245         /// Returns the the path where the buffer lives.
246         /// It is always an absolute path.
247         std::string const & filePath() const;
248
249         /** A transformed version of the file name, adequate for LaTeX.
250             \param no_path optional if \c true then the path is stripped.
251         */
252         std::string latexName(bool no_path = true) const;
253
254         /// Get thee name and type of the log.
255         std::pair<LogType, std::string> logName() const;
256
257         /// Change name of buffer. Updates "read-only" flag.
258         void setFileName(std::string const & newfile);
259
260         /// Name of the document's parent
261         void setParentName(std::string const &);
262
263         /** Get the document's master (or \c this if this is not a
264             child document)
265          */
266         Buffer const * masterBuffer() const;
267         /** Get the document's master (or \c this if this is not a
268             child document)
269          */
270         Buffer * masterBuffer();
271
272         /// Is buffer read-only?
273         bool isReadonly() const;
274
275         /// Set buffer read-only flag
276         void setReadonly(bool flag = true);
277
278         /// returns \c true if the buffer contains a LaTeX document
279         bool isLatex() const;
280         /// returns \c true if the buffer contains a DocBook document
281         bool isDocBook() const;
282         /// returns \c true if the buffer contains a Wed document
283         bool isLiterate() const;
284
285         /** Validate a buffer for LaTeX.
286             This validates the buffer, and returns a struct for use by
287             #makeLaTeX# and others. Its main use is to figure out what
288             commands and packages need to be included in the LaTeX file.
289             It (should) also check that the needed constructs are there
290             (i.e. that the \refs points to coresponding \labels). It
291             should perhaps inset "error" insets to help the user correct
292             obvious mistakes.
293         */
294         void validate(LaTeXFeatures &) const;
295
296         /// Update the cache with all bibfiles in use (including bibfiles
297         /// of loaded child documents).
298         void updateBibfilesCache();
299         /// Return the cache with all bibfiles in use (including bibfiles
300         /// of loaded child documents).
301         std::vector<support::FileName> const & getBibfilesCache() const;
302         ///
303         void getLabelList(std::vector<docstring> &) const;
304
305         ///
306         void changeLanguage(Language const * from, Language const * to);
307
308         ///
309         bool isMultiLingual() const;
310
311         ///
312         BufferParams & params();
313         BufferParams const & params() const;
314
315         /** The list of paragraphs.
316             This is a linked list of paragraph, this list holds the
317             whole contents of the document.
318          */
319         ParagraphList & paragraphs();
320         ParagraphList const & paragraphs() const;
321
322         /// LyX version control object.
323         LyXVC & lyxvc();
324         LyXVC const & lyxvc() const;
325
326         /// Where to put temporary files.
327         std::string const & temppath() const;
328
329         /// Used when typesetting to place errorboxes.
330         TexRow & texrow();
331         TexRow const & texrow() const;
332
333         ///
334         ParIterator par_iterator_begin();
335         ///
336         ParConstIterator par_iterator_begin() const;
337         ///
338         ParIterator par_iterator_end();
339         ///
340         ParConstIterator par_iterator_end() const;
341
342         /** \returns true only when the file is fully loaded.
343          *  Used to prevent the premature generation of previews
344          *  and by the citation inset.
345          */
346         bool isFullyLoaded() const;
347         /// Set by buffer_funcs' newFile.
348         void setFullyLoaded(bool);
349
350         /// Our main text (inside the top InsetText)
351         Text & text() const;
352
353         /// Our top InsetText
354         Inset & inset() const;
355
356         //
357         // Macro handling
358         //
359         /// Collect macros in paragraphs
360         void updateMacros();
361         /// Look for macro defined before par (or in the master buffer)
362         bool hasMacro(docstring const & name, Paragraph const & par) const;
363         /// Look for macro defined anywhere in the buffer (or in the master buffer)
364         bool hasMacro(docstring const & name) const;
365         /// Return macro defined before par (or in the master buffer)
366         MacroData const & getMacro(docstring const & name, Paragraph const & par) const;
367         /// Return macro defined anywhere in the buffer (or in the master buffer)
368         MacroData const & getMacro(docstring const & name) const;
369
370         /// Replace the inset contents for insets which InsetCode is equal
371         /// to the passed \p inset_code.
372         void changeRefsIfUnique(docstring const & from, docstring const & to,
373                 InsetCode code);
374
375         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
376         /// including preamble
377         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
378                 bool full_source);
379
380         /// Access to error list
381         ErrorList const & errorList(std::string const & type) const;
382         ErrorList & errorList(std::string const & type);
383
384         //@{
385         TocBackend & tocBackend();
386         TocBackend const & tocBackend() const;
387         //@}
388         
389         //@{
390         EmbeddedFiles & embeddedFiles();
391         EmbeddedFiles const & embeddedFiles() const;
392         //@}
393
394         Undo & undo();
395        
396         /// This function is called when the buffer is changed.
397         void changed() const;
398         /// This function is called when the buffer structure is changed.
399         void structureChanged() const;
400         /// This function is called when some parsing error shows up.
401         void errors(std::string const & err) const;
402         /// This function is called when the buffer busy status change.
403         void setBusy(bool on) const;
404         /// This function is called when the buffer readonly status change.
405         void setReadOnly(bool on) const;
406         /// Update window titles of all users.
407         void updateTitles() const;
408         /// Reset autosave timers for all users.
409         void resetAutosaveTimers() const;
410         ///
411         void message(docstring const & msg) const;
412
413         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
414
415         ///
416         void autoSave() const;
417         ///
418         bool writeAs(std::string const & newname = std::string());
419         ///
420         bool menuWrite();
421         ///
422         void loadChildDocuments() const;
423         /// return the format of the buffer on a string
424         std::string bufferFormat() const;
425
426         ///
427         bool doExport(std::string const & format, bool put_in_tempdir,
428                 std::string & result_file);
429         ///
430         bool doExport(std::string const & format, bool put_in_tempdir);
431         ///
432         bool preview(std::string const & format);
433         ///
434         bool isExportable(std::string const & format) const;
435         ///
436         std::vector<Format const *> exportableFormats(bool only_viewable) const;
437
438 private:
439   /// 
440         bool readFileHelper(support::FileName const & s);
441         ///
442         std::vector<std::string> backends() const;
443         /** Inserts a file into a document
444             \return \c false if method fails.
445         */
446         ReadStatus readFile(Lexer &, support::FileName const & filename,
447                             bool fromString = false);
448
449         /// Use the Pimpl idiom to hide the internals.
450         class Impl;
451         /// The pointer never changes although *pimpl_'s contents may.
452         Impl * const pimpl_;
453
454         /// A cache for the bibfiles (including bibfiles of loaded child
455         /// documents), needed for appropriate update of natbib labels.
456         mutable std::vector<support::FileName> bibfilesCache_;
457
458         frontend::GuiBufferDelegate * gui_;
459 };
460
461
462 } // namespace lyx
463
464 #endif