Skip to content

Instantly share code, notes, and snippets.

@rodrigorgs
Last active October 18, 2016 16:59
Show Gist options
  • Save rodrigorgs/427149f4672405af45886fcc86769955 to your computer and use it in GitHub Desktop.
Save rodrigorgs/427149f4672405af45886fcc86769955 to your computer and use it in GitHub Desktop.
Modifies an ODT file, replacing occurrences of [[label]] with sequential numbers (one sequence per label)
#!/usr/bin/env ruby
# enumerate-refs.rb
# Author: Rodrigo Rocha <[email protected]>
# Date: 2016-10-18
# To install the dependency, run on terminal:
# gem install rubyzip
require 'zip'
class Referencer; end
def help_and_quit
puts ' Modifies an ODT file, replacing occurrences of [[label]]'
puts 'with sequential numbers (one sequence per label).'
puts ' Example: "See [[fig-overview]] and [[fig-detail]]"'
puts 'becomes "See 1 and 2."'
puts
puts "Usage: #{$0} file.odt"
exit 1
end
class Referencer
def initialize
@last_index = 0
@hash = {}
end
def index_for(key)
index = @hash[key]
if index.nil?
@last_index += 1
@hash[key] = @last_index
index = @last_index
end
index
end
end
if __FILE__ == $0
input_path = ARGV[0]
help_and_quit if input_path.nil?
referencer = Referencer.new
Zip::File.open(input_path) do |zip_file|
entry = zip_file.glob('content.xml').first
contents = entry.get_input_stream.read
contents.gsub!(/\[\[(.*?)\]\]/) do |m|
key = $1.gsub(/<.*?>/, '').strip
referencer.index_for(key)
end
zip_file.get_output_stream('content.xml'){ |f| f.write(contents) }
zip_file.commit
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment