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