The introduction of the psalm in my Bible says it is for a director of music, which tells me this psalm was intended to be a song of praise. The audience, then, would be those joining together in corporate worship. It is written like a letter directly to God, thanking Him. Because of this, the mood of Psalm 139 is a joyful one, praising God for His creation and intimate knowledge of mankind (verses 1-4, 7-18, 23-24). Other than the author and directions to the worship leader, there is not much else in the psalm to give us locational or situational context. However, I think it was probably written in a time of peace in David's life. It is lacking the sorrowful tones of many of his other songs. Also, this psalm doesn't speak of David's enemies pressing in against him, but it does give us a clue as to what makes someone an enemy to David. David says his enemies are those who hate God (verses 21-22). He makes sure he is in right standing with the Lord before the psalm is over (verses 23-24). This tells me David wants to be sure that he does not become his own enemy. .
The main theme in this psalm is praise for God's involvement with His creation. David starts this song out by pointing to God's omnipotence (verses 1-6). Yahweh knows everything there is to know about mankind. He knows what we think, how we feel, and what we do. In His omnipotence, God is showing His extreme love and gives us our worth. It is amazing that omnipotence, being foundational to the nature of God, is a main contributor to our value as humans. The Psalmist understands this intimately. He cannot wrap his head around the thought (verses 6, 17). But, if we were able to fully understand the nature of God, why would we ever need Him?.
Next, David talks about how he cannot separate himself from the presence of God (verses 7-12). What this says is that God meets us where we are. There are so many times we feel like we have to clean our act up in order to be accepted by God.