A smart rule to move tags into groups on moving into database

Moving a tag to another database moves all records with the tag. That’s not what you want.

It’s after moving, so it’s the destination database.

Although it’s not possible to use Script Debugger’s debugging tools with it you could try Script: Comfortably developing a Smart Rule Script.

I took a look at your script. One problem is that you didn’t set in which database things should happen. See these lines:

set tagRec to get record at topTagLocation & thisTag
set destRec to get record at destinationTopLocation in database of thisRecord

In the first line the in database of part is missing. And get record at defaults to the current database which means some “weird” things will happen … and some minutes later everything will work again … and then it fails … and so on :slight_smile:

As mentioned your approach of moving the tag won’t work. I guess you tried with only one record, right? I think what you want is create location, this creates a location if it doesn’t exist, if it exists it does nothing. So instead of moving the actual tag you could use the tag’s name to create the location, leaving the tag untouched.

No idea what to do with the actual tags, though. Maybe the easiest way is to remove them from the record (set tags of thisRecord to {}) and then use a Smart Group or Rule to delete empty tags.

property defaultTopLocation : "/TagsToSort"
property topTagLocation : "/Tags/"
property maxPrefixCharacters : 2
property FileLocations : {¬
	{prefix:"rk", Toplocation:"/Research/RK.Group"}, ¬
	{prefix:"rm", Toplocation:"/Research/RM.Group"}, ¬
	{prefix:"rj", Toplocation:"/Research/RJ.Group"}}

on performSmartRule(theRecords)
	tell application id "DNtp"
		try
			set oldDelimiters to AppleScript's text item delimiters
			set AppleScript's text item delimiters to "."
			
			repeat with thisRecord in theRecords
				set theTags to tags of thisRecord
				repeat with thisTag in theTags
					set thisPrefix to item 1 of (text items of thisTag)
					if (count of characters of thisPrefix) ≤ maxPrefixCharacters then
						set thisGroupTag_Location to my retrieveTopLocation(thisPrefix) & "/" & thisTag
						set thisGroupTag to create location thisGroupTag_Location in database of thisRecord
						replicate record thisRecord to thisGroupTag		
					end if
				end repeat
			end repeat
			
			set AppleScript's text item delimiters to oldDelimiters
		on error error_message number error_number
			set AppleScript's text item delimiters to oldDelimiters
			if the error_number is not -128 then display alert "DEVONthink" message error_message as warning
		end try
	end tell
end performSmartRule

on retrieveTopLocation(prefixToTest)
	repeat with rec in my FileLocations
		if prefixToTest is prefix of rec then
			return Toplocation of rec
		end if
	end repeat
	return defaultTopLocation
end retrieveTopLocation
1 Like