Word count in Kate

Recently I've posted on how to use External Tools in Kate. I wanted to use the word count example script that is described in the article about "DCOP scripting the Kate application". But it didn't work. Of course I did not give up and finally made my version that works.

First of all, in current version of Kate (which is 2.5.6 at the moment of writing) the use of *.desktop files (as described in the article) does not work. I tried it a number of times (both in my own $HOME/.kde/share/apps/kate/scripts directory and in the global /usr/share/apps/kate/scripts directory) and could not make Kate recognize and automatically add my script to the menu. Of course if one would read thoroughly enough ... Wink Before the article there's a warning in italics that tells you what I've discovered on my own. The *.desktop files are past and you've to manually add your script in "Configuration / External Tools".

Create a new entry in Ext. Tools and add the following properties:
  • Label: Word count
  • Script: kate-wordcount.sh
  • Executable: kate-wordcount.sh
  • Mime types: <can be left empty>
  • Save: none
  • Command line name: word-count
Now create a script in a terminal and name it kate-wordcount.sh. The script should contain the following:
#!/bin/sh

kate_proc=`dcop kate\*`
kate_doc=`dcop ${kate_proc} KateDocumentManager activeDocumentNumber`
set -- `dcop ${kate_proc} EditInterface#${kate_doc} text | wc`
kdialog --title "Word count" \
  --msgbox "Lines: $1\nWords: $2\nCharacters: $3"

Put this script to a directory that is in your $PATH variable and you're all done. Clicking "Word count" in External Tools will pop up a dialog window containing the line, word and character counts of the active document in Kate.

PS: thanks to airwin for the tip with the set command. I tried to split the output of wc into variables with read, but apparently it sucks when used in a pipe (at least in sh and bash, however it works in zsh). airwin pointed out that it works if I put read in parenthesis (eg. cat somedoc.txt | wc | (read lines words chars; echo "Lines: $lines\nWords: $words\nCharacters: $chars")), but set seemed to be an even better solution.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

This does work with Kate 3.7.2 on OpenSuSE 12.1 64-bit

No matter what an end user does, external tools will not accept the script addition.

Re: This does work with Kate 3.7.2 on OpenSuSE 12.1 64-bit

I guess you meant "this doesn't work with Kate 3.7.2 on OpenSuSE 12.1 64-bit". I'd have been surprised if it did. I wrote this post over 4 years ago and probably a lot has changed both in KDE and in Kate since then.