Imam explains the matter in his famous book "an exposition on Forty Hadith" as following:
The first condition for a mujahid in his struggle that he has to observe and abide by, at this juncture and at all other stages, is to control the flight of one’s imagination, so that he can subjugate the Devil and his armies. Imagination is like a bird restless to fly, and sit on any tree it reaches.
This flight may bring about many great misfortunes. Fancy is one of the tools of the Devil, with which he enslaves man and renders him helpless. With the help of fancy, he entices men to committing villainies and indecencies.
A mujahid who is determined on self-rectification, and who has made up his mind to purify his inner self and banish satanic forces from there, should firmly hold the bridle of his imagination and let not it soar and wander about wherever it likes.
He should try to prevent his mind from nursing corrupt and sinful thoughts, and always divert it to high and noble ideals. In the beginning, it appears to be a little difficult, since Satan and his forces may glorify bad things in your eyes. But with little concentration and attention everything becomes easy.
It is possible that as an experiment you may just think for a while, and will not be able to concentrate upon an object. Whenever you see that your thoughts are stooping to lowly and mean things, turn your attention aside from them and think about the worthier and nobler things, Imam further explains.
If you have been successful in your attempts, thank God Almighty for His help, and pursue these matters further. May God, out of His mercy, open the path of spiritual progress for you, and may you be invisibly guided in the straight path. May human deeds and right conduct be made easy for you.
Be careful that vicious thoughts and vain fancies are induced by Satan, who wishes to fortify its forces in the domain of your inner self.
Read more:
Faithless people become proud of their evil deeds, Imam Khomeini explained