Skip to content

Instantly share code, notes, and snippets.

@kou1okada
Last active January 11, 2022 11:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kou1okada/33a9577909deee4f396ec8689c4ec268 to your computer and use it in GitHub Desktop.
Save kou1okada/33a9577909deee4f396ec8689c4ec268 to your computer and use it in GitHub Desktop.
wc4word.rb: wc for Microsoft Word.
#!/usr/bin/env ruby
#
# wordwc.rb - wc for Microsoft Word
# Copyright (c) 2021 Koichi OKADA. All rights reserved.
# This script is distributed under the MIT license.
#
require 'win32ole'
require 'optparse'
$conf = {
visible: true,
update: true,
lines: nil,
words: nil,
chars: nil,
default: true,
}
opts = OptionParser.new
opts.banner = "Usage: #{File.basename $0} [OPTIONS] [FILE]"
opts.on("-h", "--hide"){|v| $conf[:visible] = false}
opts.on("-n", "--no-update"){|v| $conf[:update] = false}
opts.on("-l", "--lines"){|v| $conf[:lines] = v}
opts.on("-w", "--words"){|v| $conf[:words] = v}
opts.on("-m", "--chars"){|v| $conf[:chars] = v}
opts.parse! ARGV
unless 0 < ARGV.count
puts opts.help
exit 1
end
default = $conf[:lines].nil? && $conf[:words].nil? && $conf[:chars].nil?
$conf[:lines] = $conf[:lines] || default
$conf[:words] = $conf[:words] || default
$conf[:chars] = $conf[:chars] || default
wso = WIN32OLE.new('WScript.Shell')
["USERPROFILE", "HOMEDRIVE", "HOMEPATH"].each{|k|wso.Environment("Process").setproperty("item", k, (["Process", "Volatile", "User", "System"].map{|t|wso.Environment(t).Item(k)} << ENV[k]).bsearch{|x|x!=""})}
fso = WIN32OLE.new('Scripting.FileSystemObject')
begin
wd = WIN32OLE.new('Word.Application')
wd.Visible = $conf[:visible]
wd.ScreenUpdating = $conf[:update]
module WORD_CONST; end
WIN32OLE.const_load(wd, WORD_CONST)
ARGV.each{|fn|
doc = wd.Documents.Open(fso.GetAbsolutePathName(fn))
rng = doc.Range()
line = ""
line += "\t%s" % rng.ComputeStatistics(WORD_CONST::WdStatisticLines) if $conf[:lines]
line += "\t%s" % rng.ComputeStatistics(WORD_CONST::WdStatisticWords) if $conf[:words]
line += "\t%s" % rng.ComputeStatistics(WORD_CONST::WdStatisticCharacters) if $conf[:chars]
line += "\t%s" % fn
puts line
doc.Close(false)
}
ensure
wd.Quit()
WIN32OLE.ole_free(wd)
end
WIN32OLE.ole_free(fso)
WIN32OLE.ole_free(wso)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment